O'Reilly logo

Writing Word Macros, Second Edition by Steven Roman PhD

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Replace Operation

Performing a search and replace is not much more complicated than performing a simple search. The Find object has a Replacement child object, accessible through the Replacement property. Just set the properties of the Replacement object, including any text or formatting that you want to use for the replacement. Then we run the Execute method of the Find object, using the named parameter Replace, which can take on one of three values: wdReplaceAll, wdReplace-None, or wdReplaceOne.

Here is an example that replaces each occurrence of the word “find” with the word “replace”. Note that we must clear the formatting of both the Find and the Replacement objects.

	Selection.Find.ClearFormatting
	Selection.Find.Replacement.ClearFormatting
	With Selection.Find
	   .Text = "find"
	   .Replacement.Text = "replace"
	   .Forward = True
	   .Wrap = wdFindContinue
	   .Format = False
	   .MatchCase = False
	   .MatchWholeWord = False
	   .MatchWildcards = False
	   .MatchSoundsLike = False
	   .MatchAllWordForms = False
	End With
	Selection.Find.Execute Replace:=wdReplaceAll

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required