文字列または書式設定の検索および置換

検索および置換は、 Find および Replacement オブジェクトを使用して行います。 Find オブジェクトを使用するには、まず Selection オブジェクトまたは Range オブジェクトを指定する必要があります。 ただし、 Find オブジェクトに Selection オブジェクトからアクセスした場合と、 Range オブジェクトからアクセスした場合では、検索の動作が少し異なります。

文字列を検索し、選択する

Find オブジェクトに Selection オブジェクトからアクセスした場合、検索条件に一致する文字列が検出されると、選択範囲が変更されます。 次の例では、"Hello" という単語の次の出現箇所を選択します。"Hello" という単語が見つかる前に文書の末尾に到達すると、検索は停止します。

With Selection.Find 
 .Forward = True 
 .Wrap = wdFindStop 
 .Text = "Hello" 
 .Execute 
End With

The Find object includes properties that relate to the options in the Find and Replace dialog box. You can set the individual properties of the Find object or use arguments with the Execute method, as shown in the following example.

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 オブジェクトからアクセスします。 次の使用例では、"前略" という文字列をすべて "拝啓" に置換します。 Selection オブジェクトから Find オブジェクトにアクセスするので、検索文字列が検出されると、選択範囲が変更されます。

With Selection.Find 
 .ClearFormatting 
 .Text = "hi" 
 .Replacement.ClearFormatting 
 .Replacement.Text = "hello" 
 .Execute Replace:=wdReplaceAll, Forward:=True, _ 
 Wrap:=wdFindContinue 
End With

The following example removes bold formatting in the active document. The Bold property is True for the Find object and False for the Replacement object. 書式設定を検索して置換するには、文字列の検索と置換を空の文字列 ("") に設定し、Execute メソッドの引数 FormatTrue に設定します。 The selection remains unchanged because the Find object is accessed from a Range object (the Content property returns a Range object).

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 のサポートおよびフィードバックを参照してください。