Share via


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.

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 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

Optional Parameters in Office Solutions