We help IT Professionals succeed at work.

Word vba search not working!

etech0
etech0 asked
on
 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

Comment
Watch Question

GrahamSkanRetired
CERTIFIED EXPERT
Top Expert 2012

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

Author

Commented:
November 3, 2011
xxxx
xxxx
November 4, 2011
xxxx
xxxx
xxxx
GrahamSkanRetired
CERTIFIED EXPERT
Top Expert 2012

Commented:
Sorry, I meant, can you post it as a Word document?

Author

Commented:
GrahamSkanRetired
CERTIFIED EXPERT
Top Expert 2012

Commented:
The Date function doesn't seem to work as expected.

Try

 Format(Now, "MMMM d, yyyy"),
GrahamSkanRetired
CERTIFIED EXPERT
Top Expert 2012

Commented:
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.
GrahamSkanRetired
CERTIFIED EXPERT
Top Expert 2012

Commented:
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

Author

Commented:
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

GrahamSkanRetired
CERTIFIED EXPERT
Top Expert 2012

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

Author

Commented:
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

Retired
CERTIFIED EXPERT
Top Expert 2012
Commented:
That only selects the first paragraph.

Change it to:

ActiveDocument.Range.Select

as in my code.

Author

Commented:
That did the trick!
Thanks for all your help.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.