Example: Repeated Searching

Since the range is redefined after a successful search, the process of repeated searching has a slight complication. The problem is that you cannot simply define a Range object called rng to denote the range to search and then use the Find object of rng, because a successful search would then change the search range for the next search!

Perhaps it would have been simpler if Microsoft had included a ResultRange object that represented the range of the successful search and left the original search range alone. The ResultRange object could have the Found property, which would be queried to determine whether the search was successful. In any case, in doing a repeated search, you must save the original search range (especially its endpoint) and also keep track of where the next search operation should begin.

The macro in Example 15-1 illustrates one approach to searching repeatedly through a portion of a document. To explain the purpose of this macro, let me set the stage. In the manuscript for this book, the chapter titles have the form:

Chapter XX

where XX is a chapter number and – is an en dash. Also, the titles are formatted with style Heading 1. For quickly navigating through the manuscript, I wanted to add a bookmark of the form CXX in front of each chapter title. For instance, the bookmark for Chapter 12 should be named C12.

Of course, I could do this manually (for 21 chapters), but the problem is that as the manuscript develops, I may add chapters in ...

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.