Chapter 15. The Find and Replace Objects

In this chapter:

  • Searching for Text

  • Searching for Formatting

  • The Replace Operation

  • The Execute Method

  • Example: Repeated Searching

Searching (and replacing) is one of the most commonly performed operations. The Word object model provides a Find object and a Replacement object for this purpose. The Range object and the Selection object both have a Find property that returns a Find object, which is used to search within the given range or selection (and possibly beyond).

Searching for Text

Searching for text (or formatting) amounts to little more than setting various properties of the Find object and then executing the object’s Execute method.

Incidentally, you may be wondering why there is a Find object and not simply a Find method. The main reason is that, like the Font object, the Find object retains its settings until they are changed by the programmer and can therefore be used repeatedly. This is especially important when we consider the fact that the Find object has 25 properties. If Find were a method instead of an object, you would potentially need to set all 25 properties each time you made a call to this method!

Here is an example of finding some text using the Find object from a Selection object:

 With Selection.Find .ClearFormatting .Text = "To be or not to be" .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False ...

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.