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

Get Writing Word Macros, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.