다음을 통해 공유


How to: Programmatically search for and replace text in documents

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

The Find object is a member of both the Selection and the Range objects, and you can use either one to search for text in Microsoft Office Word documents. The replace command is an extension of the find command.

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 VSTO Add-in projects for Word. For more information, see Features available by Office application and project type.

Use a Selection object

When you use a Selection object to find text, any search criteria you specify are applied only against currently selected text. If the Selection is an insertion point, then the document is searched. When the item is found that matches the search criteria, it is automatically selected.

It is important to note that the Find criteria are cumulative, which means that criteria are added to previous search criteria. Clear formatting from previous searches by using the ClearFormatting method prior to the search.

To find text using a Selection object

  1. Assign a search string to a variable.

    Dim findText As String = "find me"
    
    object findText = "find me";
    
  2. Clear formatting from previous searches.

    Application.Selection.Find.ClearFormatting()
    
    Application.Selection.Find.ClearFormatting();
    
  3. Execute the search and display a message box with the results.

    If Application.Selection.Find.Execute(findText) = True Then
        MessageBox.Show("Text found.")
    Else
        MessageBox.Show("The text could not be located.")
    End If
    
    if (Application.Selection.Find.Execute(ref findText,
        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing)) 
    { 
        MessageBox.Show("Text found.");
    } 
    else
    { 
        MessageBox.Show("The text could not be located.");
    }
    

    The following example shows the complete method.

    Private Sub SelectionFind()
        Dim findText As String = "find me"
    
        Application.Selection.Find.ClearFormatting()
    
        If Application.Selection.Find.Execute(findText) = True Then
            MessageBox.Show("Text found.")
        Else
            MessageBox.Show("The text could not be located.")
        End If
    End Sub
    
    private void SelectionFind() 
    { 
        object findText = "find me";
    
        Application.Selection.Find.ClearFormatting();
    
        if (Application.Selection.Find.Execute(ref findText,
            ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, 
            ref missing, ref missing)) 
        { 
            MessageBox.Show("Text found.");
        } 
        else
        { 
            MessageBox.Show("The text could not be located.");
        } 
    }
    

Use a Range object

Using a Range object enables you to search for text without displaying anything in the user interface. The Find object returns True if text is found that matches the search criteria, and False if it does not. It also redefines the Range object to match the search criteria if the text is found.

To find text using a Range object

  1. Define a Range object that consists of the second paragraph in the document.

    The following code example can be used in a document-level customization.

    Dim rng As Word.Range = Me.Paragraphs(2).Range
    
    Word.Range rng = this.Paragraphs[2].Range;
    

    The following code example can be used in a VSTO Add-in. This example uses the active document.

    Dim rng As Word.Range = Me.Application.ActiveDocument.Paragraphs(2).Range
    
    Word.Document document = this.Application.ActiveDocument;
    Word.Range rng = document.Paragraphs[2].Range;
    
  2. Using the Find property of the Range object, first clear any existing formatting options, and then search for the string find me.

    rng.Find.ClearFormatting()
    
    If rng.Find.Execute(findText) Then
    
    rng.Find.ClearFormatting();
    
    if (rng.Find.Execute(ref findText,
        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing)) 
    {
    
  3. Display the results of the search in a message box, and select the Range to make it visible.

        MessageBox.Show("Text found.")
    Else
        MessageBox.Show("Text not found.")
    End If
    
    rng.Select()
    
        MessageBox.Show("Text found.");
    } 
    else 
    { 
        MessageBox.Show("Text not found.");
    } 
    
    rng.Select();
    

    If the search fails, the second paragraph is selected; if it succeeds, the search criteria are displayed.

    The following example shows the complete code for a document-level customization. To use this example, run the code from the ThisDocument class in your project.

    Private Sub RangeFind()
        Dim findText As String = "find me"
    
        Dim rng As Word.Range = Me.Paragraphs(2).Range
    
        rng.Find.ClearFormatting()
    
        If rng.Find.Execute(findText) Then
            MessageBox.Show("Text found.")
        Else
            MessageBox.Show("Text not found.")
        End If
    
        rng.Select()
    End Sub
    
    private void RangeFind() 
    { 
        object findText = "find me";
    
        Word.Range rng = this.Paragraphs[2].Range; 
    
        rng.Find.ClearFormatting();
    
        if (rng.Find.Execute(ref findText,
            ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, 
            ref missing, ref missing)) 
        { 
            MessageBox.Show("Text found.");
        } 
        else 
        { 
            MessageBox.Show("Text not found.");
        } 
    
        rng.Select(); 
    }
    

    The following example shows the complete code for a VSTO Add-in. To use this example, run the code from the ThisAddIn class in your project.

    Private Sub RangeFind()
        Dim findText As Object = "find me"
    
        Dim rng As Word.Range = Me.Application.ActiveDocument.Paragraphs(2).Range
    
        rng.Find.ClearFormatting()
    
        If rng.Find.Execute(findText) Then
            MessageBox.Show("Text found.")
        Else
            MessageBox.Show("Text not found.")
        End If
    
        rng.Select()
    End Sub
    
    private void RangeFind()
    {
        object findText = "find me";
    
        Word.Document document = this.Application.ActiveDocument;
        Word.Range rng = document.Paragraphs[2].Range;
    
        rng.Find.ClearFormatting();
    
        if (rng.Find.Execute(ref findText,
            ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
            ref missing, ref missing))
        {
            MessageBox.Show("Text found.");
        }
        else
        {
            MessageBox.Show("Text not found.");
        }
    
        rng.Select();
    }
    

Search for and replace text in documents

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

To search for and replace text in documents

  1. Add the following example code to the ThisDocument or ThisAddIn class in your project.

    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);
    }
    

    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.

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