Share via


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.

Example

Private Sub SearchReplace()
    Dim FindObject As Word.Find = Application.Selection.Find
    With FindObject
        .ClearFormatting()
        .Text = "find me"
        .Replacement.ClearFormatting()
        .Replacement.Text = "Found"
        .Execute(Replace:=Word.WdReplace.wdReplaceAll)
    End With 
End Sub
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);
}

Compiling the Code

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:

See Also

Tasks

How to: Search for Text in Documents

How to: Set Search Options in Word

How to: Loop Through Found Items in Documents

How to: Restore Selections After Searches

Concepts

The Variable missing and Optional Parameters in Office Solutions