'Rename Word mailmerge fields in VBA

I want to rename mergefields in a Word document. I use the following script (based on Change value of Word MailMerge field using VBA). I run the script and I see the fieldsnames replaces by the new value. But if I toggle using Alt+F9, then I see the old name, when I toggle again is see the new name. When I execute the mailmerge, it doesn't merge.

What do I need to do to change both names?

Sub RenameMergeFields()

Dim f As Word.Field

form_old = InputBox("Vul de oude formuliernaam in.", "Formname old", "FVDL_Medewerker_Oproepkracht")
form_new = InputBox("Vul de nieuwe formuliernaam in.", "Formname new", "FVDL_Medewerker_Oproep_Omzetting")

ActiveDocument.TrackRevisions = False

If form_old <> "" And form_new <> "" Then

For Each f In ActiveDocument.Fields

  'If f.Type = wdFieldIf Then
  'End if
  
 Debug.Print "Code: " & f.Code & Chr(13)
 Debug.Print "Index: " & f.Index & Chr(13)
 
If f.Type = wdFieldMergeField Then

strReplace = Replace(f.Code, form_old, form_new)
strReplace = "{" & strReplace & "}"
f.Result.Text = strReplace

End If

Next

End If

End Sub


Solution 1:[1]

You don't need to loop through the fields. You can use Find/Replace instead. For example:

Sub RenameMergeFields()
Application.ScreenUpdating = False
Dim form_old As String, form_new As String, bTrk As Boolean, bSFC As Boolean
With ActiveDocument
  bTrk = .TrackRevisions
  .TrackRevisions = False
  bSFC = ActiveWindow.View.ShowFieldCodes
  ActiveWindow.View.ShowFieldCodes = True
  form_old = InputBox("Vul de oude formuliernaam in.", "Formname old", "FVDL_Medewerker_Oproepkracht")
  form_new = InputBox("Vul de nieuwe formuliernaam in.", "Formname new", "FVDL_Medewerker_Oproep_Omzetting")
  If form_old = "" Or form_new = "" Then Exit Sub
  With .Range.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "MERGEFIELD " & form_old
    .Replacement.Text = "MERGEFIELD " & form_new
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchWildcards = True
    .Execute Replace:=wdReplaceAll
  End With
  ActiveWindow.View.ShowFieldCodes = bSFC
  .TrackRevisions = bTrk
End With
Application.ScreenUpdating = True
End Sub

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 macropod