etech0
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?
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
Can you post the document (or a bit of it with the date that you think that it should find)?
ASKER
November 3, 2011
xxxx
xxxx
November 4, 2011
xxxx
xxxx
xxxx
xxxx
xxxx
November 4, 2011
xxxx
xxxx
xxxx
Sorry, I meant, can you post it as a Word document?
ASKER
Sure.
sample-document.doc
sample-document.doc
The Date function doesn't seem to work as expected.
Try
Format(Now, "MMMM d, yyyy"),
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.
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
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)
How do you ensure that the Selection contains the right bit of the document? Notice that my code selects the whole document.
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.)
(I got the code from an expert, so I'm not 100% clear about what each line does.)
ActiveDocument.Paragraphs(1).Range.Select
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That did the trick!
Thanks for all your help.
Thanks for all your help.