ID: Q86259
The information in this article applies to:
The following sample macros can be used to search for the occurrence of text in a Microsoft Word document.
NOTE: Microsoft provides macros "as is" without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.
This sample macro prompts you for a text string to search for and then returns the number of times the text was found in a message box. The macro starts at the top of the document and counts the total number of occurrences in the document.
Sub MAIN
StartOfDocument
counter = 0
On Error Goto bye
searchtext$ = InputBox$("Enter text to search for?")
EditFind .Find = searchtext$, .Direction = 0
If Not EditFindFound() Then
MsgBox "Search Text Not Found"
Goto bye
End If
While EditFindFound()
counter = counter + 1
EditFind .Find = searchtext$, .Direction = 0
Wend
MsgBox searchtext$ + " was found" + Str$(counter) + "time(s)"
bye:
End Sub
Sub MAIN
StartOfDocument
counter = 0
On Error Goto bye
searchtext$ = InputBox$("Enter text to search for?")
EditFind .Find = searchtext$, .Direction = 2
If Not EditFindFound() Then
MsgBox "Search Text Not Found"
Goto bye
End If
While EditFindFound()
counter = counter + 1
EditFind .Find = searchtext$, .Direction = 2
Wend
MsgBox searchtext$ + " was found" + Str$(counter) + "time(s)"
bye:
End Sub
Make the following substitutions in the Word 2.x macro:
EditSearch .Search = searchtext$, .Direction = 2
If Not EditSearchFound() Then
While EditSearchFound()
If you want to apply a format or perform commands when the search text is found, add the appropriate commands below the EditFind command. For example, in Word 2.x:
EditFind .Find = searchtext$, .Direction = 2
FormatCharacter .Bold = 1 'Makes search text bold
While EditFindFound()
counter = counter + 1
EditFind .Find = searchtext$, .Direction = 2
FormatCharacter .Bold = 1 'Makes search text bold
Wend
If the search text is found, the text formatting is changed to bold and
the counter increments by 1. Other WordBasic commands can be used in place
of the line that reads "FormatCharacter .Bold = 1." (WordBasic commands
entered below the EditFind command are executed when the search text is
found.)
"Using WordBasic," by WexTech Systems and Microsoft, pages 180-181
"Microsoft Word for Windows and OS/2 Technical Reference," pages 200, 224-225, 286
Kbcategory: kbusage kbmacro KBSubcategory: Additional query words: 1.0 1.10 1.10a 2.0 2.0a 2.0a-cd 2.0 2.0c 6.0 6.0a 6.0c 7.0 7.0a 6.0.1 cwinword2 word95 winword msgbox search loop editsearchfound search macword word7 word6 find while editfindfound
Keywords : winword macword word6 winword2 word95 macword5
Version : WINDOWS: 1.0, 1.1, 1.1a, 2.0, 2.0a, 2.0a-CD, 2.0b, 2.0c, 6.0, 6.0a, 6.0c, 7.0, 7.0a; MACINTOSH:3.0,3.01,3.02,4.0,5.0,5.10,6.0,6.0.1,6.0.1a;
Last Reviewed: November 18, 1997