Wordマクロで選択範囲内だけ置換するときの注意
選択範囲内の文字の置換を行うには次のようにします。
Sub 選択範囲のアをイに置換()
With Selection.Find
.Text = "ア"
.Replacement.Text = "イ"
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
With Selection.Find
.Text = "ア"
.Replacement.Text = "イ"
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
この場合、次のようなメッセージが出ることがあります。
選択範囲の検索が終了しました。○個の項目を置換しました。文書の残りの部分も検索しますか?
ここで「いいえ」をクリックすればよいのですが、うっかり「はい」をクリックすると選択範囲外の文字まで置換されてしまいます。
このようなときは「Find.Wrap」プロパティに「wdFindStop」を指定します。
Sub 選択範囲のアをイに置換()
With Selection.Find
.Text = "ア"
.Replacement.Text = "イ"
.Wrap = wdFindStop
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
With Selection.Find
.Text = "ア"
.Replacement.Text = "イ"
.Wrap = wdFindStop
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
これならば実行後にダイアログが出ることなく終了します。





















最近のコメント