Export (0) Print
Expand All

How to: Search for and Replace Text in Documents

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Project type

  • Document-level projects

  • Application-level projects

Microsoft Office version

  • Word 2003

  • Word 2007

For more information, see Features Available by Application and Project Type.

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.

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(Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object) 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:
© 2015 Microsoft