
Originally Posted by
R. Racoon
Using Ctrl-F in a Word document opens a new search box, that will show each of the hits for an entered keyword. It also lists X results, where X = the number of hits.
My question is: What code can be used to capture that X quantity in a VBA macro, in order to inform the user how many results were found for a search macro?
Sub Test()
MsgBox CountWordOccurrences("Test")
End Sub
Function CountWordOccurrences(strText)
Dim lngIndex As Long
Dim oRng As Range
Set oRng = ActiveDocument.Range
With oRng.Find
.Text = strText
.MatchCase = False
.Forward = True
.Wrap = wdFindStop
While .Execute
lngIndex = lngIndex + 1
oRng.Collapse wdCollapseEnd
Wend
CountWordOccurrences = lngIndex
End With
lbl_Exit:
Exit Function
End Function