Link to home
Start Free TrialLog in
Avatar of etech0
etech0Flag for United States of America

asked on

Word vba search not working!

 I have the following code which is supposed to search for the current date and then run an if statement checking     If Selection.Find.Found Then.
I know the document contains the date, but my If statement keeps returning as False.
Can anyone help?

Selection.Find.ClearFormatting
With Selection.Find
    .Text = Format(Date, "MMMM d, yyyy")
    .Forward = True
End With
Selection.Find.Execute

Open in new window

Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Can you post the document (or a bit of it with the date that you think that it should find)?
Avatar of etech0

ASKER

November 3, 2011
xxxx
xxxx
November 4, 2011
xxxx
xxxx
xxxx
Sorry, I meant, can you post it as a Word document?
The Date function doesn't seem to work as expected.

Try

 Format(Now, "MMMM d, yyyy"),
I have now tested your code on another system and it works OK.

The Date function was returning December 31, 1899 on the first machine, so unless your system has the same error, I don't know what problem you are getting.
I've now restarted Word on the first system, and the Date function is working properly again. This code prints True in the Immediate window.
Sub FindText()
ActiveDocument.Range.Select
Selection.Find.ClearFormatting
With Selection.Find
    .Text = Format(Date, "MMMM d, yyyy")
    .Forward = True
    Debug.Print .Execute
End With

End Sub

Open in new window

Avatar of etech0

ASKER

I have updated code, but it still returns selection.find.found = false.
With Selection.Find
        .Text = Format(Now, "MMMM d, yyyy")
        .Forward = True
    End With
    Selection.Find.Execute
    If Selection.Find.Found Then (proceed with my macro)

Open in new window

How do you ensure that the Selection contains the right bit of the document? Notice that my code selects the whole document.
Avatar of etech0

ASKER

It does this before searching - does that select the entire document?

(I got the code from an expert, so I'm not 100% clear about what each line does.)
ActiveDocument.Paragraphs(1).Range.Select

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of etech0

ASKER

That did the trick!
Thanks for all your help.