Search code examples
vbams-wordmergefield

How to create a mergefield with a formula containing mergefields


I want to build mergefields that decide between the data coming from two different mergefields. For example «field_1» should contain:

IF «field_1» > "" "«field_1»" "«field_2»"

I tried it the following way:

Sub createField()
   Dim mergeString As String
   mergeString = "IF{MERGEFIELD field_1}>"""" ""{MERGEFIELD field_1}""""{MERGEFIELD field_2}"""

   Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=False
   Selection.TypeText Text:=mergeString
End Sub

also with insertFormula:

Sub createField()
    Dim mergeString As String
    mergeString = "IF{MERGEFIELD field_1}>"""" ""{MERGEFIELD field_1}""""{MERGEFIELD field_2}"""

   Selection.InsertFormula Formula:= mergeString
End Sub

but it's just a mess.


Solution

  • Unfortunately, this code will just insert the text as a regular string rather than as Mergefields. If you insert the fields in Word manually, you can use the Ctrl+F9 key to insert the braces to mark that the contents are a field rather than regular text.

    To insert the field that you want directly in to Word, you would either need to construct the fields manually (using Ctrl+F9 and typing the field names) or you could use the option to insert the If Statement with Placeholder text then replace the Placeholders with the required Fields. You'd need to follow the same process to create the Field in VBA.

    Sub createField() Dim showState As Boolean showState = ActiveWindow.View.ShowFieldCodes

    Dim ifField As MailMergeField
    Set ifField = ActiveDocument.MailMerge.Fields.AddIf(Range:=Selection.Range, MergeField:= _
        "Name", Comparison:=wdMergeIfNotEqual, CompareTo:="", TrueText:="FieldIfTrue", _
        FalseText:="FieldIfFalse")
    ifField.Select
    ActiveWindow.View.ShowFieldCodes = True
    
    With Selection.Find
        .ClearFormatting
        .Text = "FieldIfTrue"
        .Replacement.Text = ""
        .Forward = True
        .Format = False
        .Execute
    End With
    
    ActiveDocument.Fields.Add Range:=Selection.Range, Type:=wdFieldMergeField, Text:="""Name"""
    
    With Selection.Find
        .Text = "FieldIfFalse"
        .Replacement.Text = ""
        .Forward = True
        .Format = False
        .Execute
    End With
    
    ActiveDocument.MailMerge.Fields.Add Range:=Selection.Range, Name:="OtherName"
    
    Selection.Fields.Update
    ActiveWindow.View.ShowFieldCodes = showState
    

    End Sub