共用方式為


HOW TO:搜尋和取代文件中的文字

更新:2007 年 11 月

適用於

本主題中的資訊僅適用於指定的 Visual Studio Tools for Office 專案和 Microsoft Office 版本。

專案類型

  • 文件層級專案

  • 應用程式層級專案

Microsoft Office 版本

  • Word 2003

  • Word 2007

如需詳細資訊,請參閱依應用程式和專案類型提供的功能

使用 Find 物件在 Microsoft Office Word 文件中逐一搜尋特定的文字、格式或樣式,並使用 Replacement 屬性取代任何找到的項目。

下列程式碼會搜尋目前的選取範圍,並使用字串 Found 取代找到的所有 find me 字串。若要使用這個範例,請從專案中的 ThisDocument 或 ThisAddIn 類別中執行。

範例

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

編譯程式碼

Find 類別具有 ClearFormatting 方法,而 Replacement 類別也有自己的 ClearFormatting 方法。在執行尋找和取代作業時,必須使用這兩個物件的 ClearFormatting 方法。如果您只在 Find 物件上使用它,則可能會在取代文字中得到非預期的結果。

使用 Find 物件的 Execute 方法取代每一個找到的項目。若要指定所要取代的項目,請使用 Replace 參數。這個參數可以是下列其中一個 WdReplace 值:

請參閱

工作

HOW TO:在文件中搜尋文字

HOW TO:在 Word 中設定搜尋選項

HOW TO:在文件中找到的項目之間執行迴圈

HOW TO:在搜尋後還原選取

概念

了解 Office 方案中的選擇性參數