We help IT Professionals succeed at work.

Word vba search for current date

etech0
etech0 asked
on
I'm looking for VBA code that will search the document, checking if today's date appears anywhere.
Comment
Watch Question

Sub FindWords()

    ActiveDocument.Paragraphs(1).Range.Select

    Selection.Find.ClearFormatting

    With Selection.Find

        .Text = Str(Date)
        .Forward = True

    End With

    Do While True

        Selection.Find.Execute

        If Selection.Find.Found Then

            intFound = intFound + 1

        Else

            Exit Do

        End If

    Loop

    MsgBox intFound & " item(s) found!"

End Sub

Author

Commented:
Thanks!
Can you edit it to search for the date in this format: November 3, 2011?
Thanks!

Author

Commented:
Thanks!
Sorry, I'm so busy that I havn't answer your question.
if you want  search for the date in this format: November 3, 2011, like this:
 
Sub FindWords()

    ActiveDocument.Paragraphs(1).Range.Select

    Selection.Find.ClearFormatting

    With Selection.Find

        .Text = "2011-10-03"
        .Forward = True

    End With

    Do While True

        Selection.Find.Execute

        If Selection.Find.Found Then

            intFound = intFound + 1

        Else

            Exit Do

        End If

    Loop

    MsgBox intFound & " item(s) found!"

End Sub

Open in new window


if you want to it deal with  dnamic date, just replace  
.Text = "2011-10-03"      to    .Text =  Format(Date, "YYYY-MM-DD")

call 'Date' will return the date of today, and  'Format ' will transform  it  to string.

for example , today is 2011-11-08,  the word text is :
Aaaaaa 2011-11-08 bbbbbbbbbb 2011-11-08  cccccc 2011-11-7 2011-10-03

the vba code is:
 
Sub FindWords()

    ActiveDocument.Paragraphs(1).Range.Select

    Selection.Find.ClearFormatting

    With Selection.Find

        .Text = Format(Date, "YYYY-MM-DD")
        .Forward = True

    End With

    Do While True

        Selection.Find.Execute

        If Selection.Find.Found Then

            intFound = intFound + 1

        Else

            Exit Do

        End If

    Loop

    MsgBox intFound & " item(s) found!"

End Sub

Open in new window


the result is:
 vba
if tomorrow you run the code , there will be 0 items found. Hope it helps.

best regards.

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