Englishman Bob
Englishman Bob

Reputation: 483

Using Macros in Search and Replace Word VBA

I am trying to develop a piece of code that will pull certain names (Kennedy, Nixon, etc) from a text and replace them with names with markers (@Kennedy, @Nixon. Due to the time involved I would like to use an array. I have tried multiple examples, but have had no luck. The best model I can find is below:

Sub Macro1()

Dim i As Variant
Dim NameOrig As Variant
Dim NameSub As Variant
NameOrig = Array("McGee", "NIXON", "KENNEDY")
NameSub = Array("@McGee", "@NIXON", "@KENNEDY")
With ActiveDocument.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Forward = True
  .Wrap = wdFindContinue
  .Format = True
  For i = 1 To UBound(NameOrig)
    .Text = NameOrig(i)
    .Replacement.Text = NameSub(i)
    .Execute Replace:=wdReplaceAll
  Next
End With
End Sub

Ultimately I end up with a Run-Time error'438': Object doesn't support this property or method. Is there a way to fix this? Alternately is there another piece of code that would actually function.

Upvotes: 0

Views: 90

Answers (1)

macropod
macropod

Reputation: 13505

You need to use either 'ActiveDocument.Content.Find' or 'ActiveDocument.Range.Find'. You also don't need 'Dim NameSub As Variant', 'NameSub = Array("@McGee", "@NIXON", "@KENNEDY")', or '.Replacement.Text = NameSub(i)'. Finally, unless you've set 'Option Base 1', if you don't start off your loop at 0, you'll miss the first item. Try:

Sub Macro1()
Dim i As Long, NameOrig As Variant
NameOrig = Array("McGee", "NIXON", "KENNEDY")
With ActiveDocument.Range.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Forward = True
  .Wrap = wdFindContinue
  .Format = True
  .Replacement.Text = "@^&"
  For i = 0 To UBound(NameOrig)
    .Text = NameOrig(i)
    .Execute Replace:=wdReplaceAll
  Next
End With
End Sub

Upvotes: 3

Related Questions