tonys
tonys

Reputation: 21

Search and Replace Multiple Words

I already have the code to do a search and replace in Microsoft Word using a VBA macro, but at the moment, my code is copying and pasting the same function multiple times.

What I would like to do is have an dictionary of words that need to be replaced, so for example:

old_word: new_word

Then I have the VBA script to loop through and make the necessary changes in the document.

My code for now is and repeats for each new word pair.

Sub change_words()

   With Selection.Find
        .Text = "optimize"
        .Replacement.Text = "optimise"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchWholeWord = True
   End With

   Selection.Find.Execute Replace:=wdReplaceAll

   With Selection.Find
        .Text = "utilized"
        .Replacement.Text = "utilised"
        .Forward = True
        .Wrap = wdFindContinue
        .MatchWholeWord = True
   End With

   Selection.Find.Execute Replace:=wdReplaceAll

End Sub 

Many thanks in advance

Upvotes: 2

Views: 4528

Answers (1)

Dave
Dave

Reputation: 4356

Sub change_words(ByVal findWord, byVal replaceWord)

   With Selection.Find
        .Text = findWord
        .Replacement.Text = replaceWord
        .Forward = True
        .Wrap = wdFindContinue
        .MatchWholeWord = True
   End With
   Selection.Find.Execute Replace:=wdReplaceAll
End Sub 

If you change your function to accept parameters as shown, you can call it in a loop, and (for example) pass in the values you want like so:

Dim myDict : Set myDict = CreateObject("Scripting.Dictionary")
myDict("optimize") = "optimise"
myDict("utilized") = "utilised"
For myLoop = 0 to myDict.Count - 1
    change_words myDict.Keys()(myLoop), myDict.Items()(myLoop)
Next

That should allow you to reuse the code without repeating it.

Upvotes: 4

Related Questions