Export (0) Print
Expand All

How to: Search for and Replace Text in Documents

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

Applies to: The information in this topic applies to document-level projects and application-level projects for Word 2007 and Word 2010. For more information, see Features Available by Office Application and Project Type.

The following code searches the current selection and replaces all of the occurrences of the string find me with the string Found. To use this example, run it from the ThisDocument or ThisAddIn class in your project.


private void SearchReplace()
{
    Word.Find findObject = Application.Selection.Find;
    findObject.ClearFormatting();
    findObject.Text = "find me";
    findObject.Replacement.ClearFormatting();
    findObject.Replacement.Text = "Found";

    object replaceAll = Word.WdReplace.wdReplaceAll;
    findObject.Execute(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);
}


The Find class has a ClearFormatting method, and the Replacement class 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 use it only on the Find object, you might get unanticipated results in the replacement text.

Use the Execute method of the Find object to replace each found item. To specify which items to replace, use the Replace parameter. This parameter can be one of the following WdReplace values:

Community Additions

ADD
Show:
© 2014 Microsoft