1. Home
  2. Computing & Technology
  3. Visual Basic

VBA - The Word Working Partner - Part 3

By Dan Mabbutt, About.com

5 of 7

Automate Find and Replace Example - Page 3

Since part of Paul's problem was that his macro was simply too long, the first thing to notice is that setting all of the Find properties (.Forward = True, .Wrap = wdFindContinue and so forth) doesn't have to be done over and over. Since there is no guarantee what the current state of the propeties might be when the subroutine is entered (for example, MatchWholeWord defaults to the state of the last global find executed), it might be a good idea to set them once and this is why the recorded macro does that. But once is usually all you need.

But this very minor change won't help Paul enough. The key to coding a solution is to note that the actual replacement takes place when the Execute method of the Find object is executed. Then you can code a loop with different Find.Text and Find.Replacement.Text objects and an Execute for each of them.

Something like this ...

~~~~~~~~~~~~~~~~~~~~~~~~~
<Start of loop>
  Find.Text = <find text>
  Find.Replacement.Text = <replacement text>
  Selection.Find.Execute Replace:=wdReplaceAll
<End of loop>
~~~~~~~~~~~~~~~~~~~~~~~~~

Explore Visual Basic
By Category
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Visual Basic
  4. Learn VB 6
  5. Learn VBA
  6. VBA - The Word Working Partner - Part 3

©2009 About.com, a part of The New York Times Company.

All rights reserved.