Export (0) Print
Expand All
Expand Minimize

How to: Search for and Replace Text in Documents

NoteNote

Some code examples in this topic use the this or Me keyword or the Globals class in a way that is specific to document-level customizations, or they rely on features of document-level customizations such as host controls. These examples can be compiled only if you have the required applications installed. For more information, see Features Available by Product Combination.

Use the Find object to loop through a Microsoft Office Word 2003 document searching for specific text, formatting, or style, and use the Replacement object to replace any of the items found.

The following code searches a selection and replaces all of the occurrences of the string find me with the string Found.

Example

Private Sub SearchReplace()
    Application.Selection.Find.ClearFormatting()
    Application.Selection.Find.Text = "find me"

    Application.Selection.Find.Replacement.ClearFormatting()
    Application.Selection.Find.Replacement.Text = "Found"

    Application.Selection.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll)
End Sub

Compiling the Code

The Find object has a ClearFormatting method and the Replacement object also has its own ClearFormatting method. When you are performing find-and-replace operations, you must use the ClearFormatting method of both objects. If you only use it on the Find operation, you might replace the text with unanticipated results.

Use the Execute method to replace each found item. The Execute method has a WdReplace enumeration that consists of three additional enumerations:

See Also

Community Additions

ADD
Show:
© 2014 Microsoft