3
votes

I'm trying to search through a Word document and replace a specific string (Using a hardcoded value of "Special" for now) with a specified value. The macro clearly shows that it finds the correct text in the Word editor, but the replacement functionality isn't working. This is my absolute first VBA experience, so I'd love some help if possible. The following code is the macro...

    Sub Test()
'
' Test Macro
'
'
    Documents.Open FileName:="C:\Users\abensch\Documents\NANTDocMerge\DMID - Backups\System Clock Ability.docx", _
        ConfirmConversions:=False, _
        ReadOnly:=False, AddToRecentFiles:=False, _
        PasswordDocument:="", PasswordTemplate:="", _
        Revert:=False, WritePasswordDocument:="", _
        WritePasswordTemplate:="", _
        Format:=wdOpenFormatAuto, _
        XMLTransform:=""
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "Special"
        .Replacement.Text = "Potato"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute

End Sub

I'm not sure that most of the specified parameters in the Select.Find are necessary, and removing them doesn't seem to influence the performance of the macro, but I figured I'd leave them in to be safe. I'm wondering if it may be a Word formatting issue, although I tried to remove all formatting with the two ClearFormatting calls.

1

1 Answers

4
votes

If you want to do a Replace all then change

Selection.Find.Execute

to

Selection.Find.Execute Replace:=wdReplaceAll

If you want to just replace the first instance and not all then use this

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "Special"
    .Replacement.Text = "Potato"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
With Selection
    If .Find.Forward = True Then
        .Collapse Direction:=wdCollapseStart
    Else
        .Collapse Direction:=wdCollapseEnd
    End If
    .Find.Execute Replace:=wdReplaceOne
End With