I’m Trying the change the mailmerge field names dynamically in VBA, I created this code but it removes the fields or its not working properly, could not find a solution.
Here I used columnMapping dictionary to keep the new headers.
Actual problem is the mapped DB have different column names hence I’m trying to replace the field names dynamically.
Set columnMapping = CreateObject("Scripting.Dictionary")
columnMapping("Header1") = "New_Header"
For Each fld In doc.MailMerge.Fields
' Extract the field name from the field text
oldName = Trim(Replace(Replace(fld.Code.Text, "MERGEFIELD", ""), "{", ""))
oldName = Trim(Replace(oldName, "}", ""))
' Check if the field name exists in the mapping
If columnMapping.Exists(oldName) Then
' Create the new field name with appropriate replacements
newName = "{ MERGEFIELD " & columnMapping(oldName) & " }"
' Replace the field text with the new field name
fld.Code.Text = newName
Debug.Print newName
End If
Next fld