View Full Version : Output of Number of Hits in a Search Macro
R. Racoon
01-27-2025, 02:39 PM
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?
June7
01-27-2025, 06:15 PM
Bing search: "word vba search for string count" has couple results including AI generated code. Check this out https://stackoverflow.com/questions/5645762/word-vba-count-word-occurrences
Aussiebear
01-28-2025, 02:54 AM
Maybe try this:
Sub CountWordOccurrences()
Dim WordToFind As String
Dim WordCount As Long Dim i As Long
Dim FoundRange As Range
' Get the word to find from the user
WordToFind = InputBox("Enter the word to find:", "Find Word")
' Exit if the user cancels the input box
If WordToFind = "" Then
Exit Sub
' Make the word case-insensitive for the search
WordToFind = LCase(WordToFind)
' Loop through each word in the document
For i = 1 To ActiveDocument.Words.Count
' Check if the current word matches the word to find
If LCase(ActiveDocument.Words(i)) = WordToFind Then
WordCount = WordCount + 1
End If
Next i
' Display the result in a message box
MsgBox "The word '" & WordToFind & "' occurs " & WordCount & " times in the document.", vbInformation
End If
End Sub
gmaxey
01-28-2025, 02:45 PM
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
Aussiebear
01-28-2025, 03:07 PM
Hmmm.... i was close but no cigar.:bow:
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.