How to: Search for and Replace Text in Documents
Some code examples in this topic use the this or Me keyword or the
Use theobject to loop through a Microsoft Office Word 2003 document searching for specific text, formatting, or style, and use the 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.
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 of both objects. If you only use it on the Find operation, you might replace the text with unanticipated results.
Use themethod to replace each found item. The Execute method has a enumeration that consists of three additional enumerations: