Finding out how many times some text appears in a document

Article contributed by Jonathan West

You can find out how often a particular phrase appears in a document with a fairly simple VBA routine. Paste the following code into the VBA editor and run it.

Public Sub CountOccurrences()

Dim iCount As Long
Dim strSearch As String

strSearch = InputBox$("Type in the text you want to search for.")
iCount = 0

With ActiveDocument.Content.Find
    .Text = strSearch
    .Format = False
    .Wrap = wdFindStop
    Do While .Execute
        iCount = iCount + 1
End With

MsgBox Chr$(34) & strSearch & Chr$(34) & " was found " & _
        iCount & " times."

End Sub