Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Word Tasks
 How to: Search for and Replace Text...
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
Visual Studio Tools for the Microsoft Office System
How to: Search for and Replace Text in Documents

NoteNote

Some code examples in this topic use the this or Me keyword or the Globals class in a way that is specific to document-level customizations, or they rely on features of document-level customizations such as host controls. These examples can be compiled only if you have the required applications installed. For more information, see Features Available by Product Combination.

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

The following code searches a selection and replaces all of the occurrences of the string find me with the string Found.

Example

Visual Basic
Private Sub SearchReplace()
    Application.Selection.Find.ClearFormatting()
    Application.Selection.Find.Text = "find me"

    Application.Selection.Find.Replacement.ClearFormatting()
    Application.Selection.Find.Replacement.Text = "Found"

    Application.Selection.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll)
End Sub
C#
private void SearchReplace() 
{ 
    object replaceAll = Word.WdReplace.wdReplaceAll; 

    Application.Selection.Find.ClearFormatting(); 
    Application.Selection.Find.Text = "find me"; 

    Application.Selection.Find.Replacement.ClearFormatting(); 
    Application.Selection.Find.Replacement.Text = "Found"; 

    Application.Selection.Find.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 object has a ClearFormatting method and the Replacement object 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 only use it on the Find operation, you might replace the text with unanticipated results.

Use the Execute method to replace each found item. The Execute method has a WdReplace enumeration that consists of three additional enumerations:

See Also

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
Page view tracker