Using the Find Object in Word 2010
Handy Programming Tips for Microsoft Word 2010: Learn how to use the properties and methods of the Find object in Microsoft Word 2010.
Applies to: Microsoft Word 2010
Published: May 2011
Provided by: Frank Rice, Microsoft Corporation
The Find object specifies the criteria for a "find" operation. The properties and methods of the Find object correspond to the options in the Find and Replace dialog box. In this topic, you programmatically use various properties and methods of the Find object to search for specific text in a document and then perform actions on that text. To complete this task, you must do the following:
Add the Code to the Visual Basic Editor
In this task, you add programming code that shows how to use several properties and methods of the Find object.
To add code to the Visual Basic Editor
Start Word 2010.
On the Developer tab, click Visual Basic to open the Visual Basic Editor.
If you do not see the Developer tab in Word 2010, click the File tab, and then click Options. In the categories pane, click Custom Ribbon, select Developer, and then click OK.
In the Projects pane, click ThisDocument.
Paste or type the following Microsoft Visual Basic for Applications (VBA) code into the module window.
Sub DemoFind() ' Set up a search, in the random text, for ' "tab Most" Dim fnd As Find Set fnd = Content.Find fnd.Text = "tab Most" ' Ignore punctuation and white space. In the document, ' the text appears as "tab. Most". This will still find ' a match. fnd.IgnorePunct = True fnd.IgnoreSpace = True ' Highlight the found text. fnd.HitHighlight fnd.Text, vbYellow, vbRed ' Now clear the highlighting. fnd.ClearHitHighlight ' Match the text "th" only when it appears at the beginning ' of a word: fnd.MatchPrefix = True fnd.Text = "th" fnd.HitHighlight fnd.Text, vbYellow, vbRed ' Now clear the highlighting. fnd.ClearHitHighlight ' Match the text "th" only when it appears at the end ' of a word: fnd.MatchPrefix = False fnd.MatchSuffix = True fnd.Text = "th" fnd.HitHighlight fnd.Text, vbYellow, vbRed ' Now clear the highlighting. fnd.ClearHitHighlight End Sub
Test the Solution
In this task, you add random text to the document and then step through the VBA code that finds and highlights specific text.
To run the code
Read through the code to form an idea of the actions that it performs.
In the document, type the following command (without the quotation marks). This adds five paragraphs of five sentences to the document.
Drag the Visual Basic Editor window to the right side of your monitor.
Drag the Word window to the left side of your monitor and adjust the windows until you can see them both.
Press F8 to step through the code line-by-line and watch as the various properties and methods run.