This documentation is archived and is not being maintained.

How to: Search for and Replace Text in Documents


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.


private void SearchReplace() 
    object replaceAll = Word.WdReplace.wdReplaceAll; 

    Application.Selection.Find.Text = "find me"; 

    Application.Selection.Find.Replacement.Text = "Found"; 

        ref missing, ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref replaceAll, ref missing, ref missing, ref missing, ref missing);

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