HOW TO:搜尋和取代文件中的文字
使用 Find 物件在 Microsoft Office Word 文件中逐一搜尋特定的文字、格式或樣式,並使用 Replacement 屬性取代任何找到的項目。
**適用於:**本主題中的資訊適用於 Word 2007 和 Word 2010 的文件層級專案和應用程式層級專案。如需詳細資訊,請參閱依 Office 應用程式和專案類型提供的功能。
下列程式碼會搜尋目前的選取範圍,並使用字串 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 值:
wdReplaceAll 會取代所有找到的項目
wdReplaceNone 不會取代任何找到的項目
wdReplaceOne 會取代第一個找到的項目