Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Word Solutions
 How to: Search for and Replace Text...
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
Microsoft Visual Studio Tools for the Microsoft Office system (version 3.0)
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.

Visual Basic
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
C#
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:

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker