MS WORD VBA Find Replace text using a variable

15,483

A quick search from google finds this link http://msdn.microsoft.com/en-us/library/office/aa211953(v=office.11).aspx

I tried this on a simple document to find and replace text

With ActiveDocument.Content.Find
    .Forward = True
    .Wrap = wdFindStop
    .Execute FindText:="Text", ReplaceWith:="Tax", Replace:=wdReplaceAll

That replaces all occurence of Text with Tax .... is this what you're after ??

Works with variables too

OldWord = "VAT"
NewWord = "Text"

With ActiveDocument.Content.Find
    .Forward = True
    .Wrap = wdFindStop
    .Execute FindText:=OldWord, ReplaceWith:=NewWord, Replace:=wdReplaceAll, Matchcase:=True
End With

Add , Matchcase:=True at end to fix case problem (modified now above)

3rd Modification results in this

Dim strLastname As String   ' from dialogue box "BoxLastname" field
strLastname = BoxLastname.Value

OldWord = "Name"
NewWord = strLastName

With ActiveDocument.Content.Find
    .Forward = True
    .Wrap = wdFindStop
    .Execute FindText:=OldWord, ReplaceWith:=NewWord, Replace:=wdReplaceAll, Matchcase:=True
End With
Share:
15,483
Niala Celdak
Author by

Niala Celdak

Updated on June 04, 2022

Comments

  • Niala Celdak
    Niala Celdak almost 2 years

    I have a variable (strLastname) that I use to send a string to a bookmark. That works well. I also wish to use that variable to replace temporary text "Name>" in a long document.

    This is what I have now.

      Sub cmdOK_Click()
        Dim strLastname As String   ' from dialogue box "BoxLastname" field
        strLastname = BoxLastname.Value
    ....
      End sub
    

    The macro that does not work:

    Sub ClientName()
    
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "Name>"
        .Replacement.Text = strLastname??????
    
                 'Selection.TypeText (strLastname) ????
                  'How to use the variable from the Dialogue Box - strLastname????
    
         End With
      Selection.Find.Execute Replace:=wdReplaceAll
    End Sub
    

    I tried .Replacement.Text = strLastname and .Replacement.Text = BoxLastname.Value but no one work.