尋找及取代是由 Find 和 Replacement 物件公開的。 Find 物件是來自 Selection 物件和 Range 物件。 尋找動作會根據您是從 Selection 物件或 Range 物件存取 Find 物件而稍微不同。
尋找並選取文字
如果 Find 物件是從 Selection 物件存取的,找到尋找準則後,就會變更選取範圍。 下列範例會選取下一個出現的 「Hello」 一字。如果在找到 「Hello」 這個字之前到達檔結尾,就會停止搜尋。
With Selection.Find
.Forward = True
.Wrap = wdFindStop
.Text = "Hello"
.Execute
End With
Find 物件含有一些與 [尋找及取代] 對話方塊中選項相關的屬性。 您可以設定 Find 物件的個別屬性,或使用引數搭配 Execute 方法,如下列範例所示。
Selection.Find.Execute FindText:="Hello", _
Forward:=True, Wrap:=wdFindStop
尋找文字但不變更選取範圍
如果 Find 物件是從 Range 物件存取的,找到尋找準則後,不會變更選取範圍,但是會重新定義 Range 。 下列範例會在使用中文件內找出第一個 "blue" 一詞。 如果尋找作業成功,就會重新定義範圍並將粗體格式設定套用至 "blue" 一詞。
With ActiveDocument.Content.Find
.Text = "blue"
.Forward = True
.Execute
If .Found = True Then .Parent.Bold = True
End With
下列範例會使用 Execute 方法的引數,執行與上一個範例相同的結果。
Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:="blue", Forward:=True
If myRange.Find.Found = True Then myRange.Bold = True
使用 Replacement 物件
The Replacement object represents the replace criteria for a find and replace operation. Replacement物件的屬性和方法會對應至 [編輯] 功能表) 中 [尋找和取代] 對話方塊 (選項。
Replacement 物件是來自 Find 物件。 下列範例會將所有 "hi" 取代為 "hello" 一詞。 因為 Find 物件是從 Selection 物件存取的,所以找到尋找準則後,就會變更選取範圍。
With Selection.Find
.ClearFormatting
.Text = "hi"
.Replacement.ClearFormatting
.Replacement.Text = "hello"
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
下列範例會移除使用中文件內的粗體格式設定。 Find物件的Bold屬性為True,Replacement物件為False。 若要尋找並取代格式設定,請將 find and replace text 設定為空字串 (「」) ,並將Execute方法的Format引數設定為True。 選取範圍保持不變,因為 Find 物件是從 Range 物件存取, (Content 屬性會傳回 Range 物件) 。
With ActiveDocument.Content.Find
.ClearFormatting
.Font.Bold = True
With .Replacement
.ClearFormatting
.Font.Bold = False
End With
.Execute FindText:="", ReplaceWith:="", _
Format:=True, Replace:=wdReplaceAll
End With
支援和意見反應
有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應。