How do I insert a mergefield into an If..else statement in VBA using Word MailMerge?

后端 未结 1 636
执念已碎
执念已碎 2020-12-22 03:55

The below macro will input the field heading followed by the field value. The If statement should check the value of the field and if its greater than 30 the actual value is

1条回答
  •  庸人自扰
    2020-12-22 04:56

    As far as I know, the only way to insert a nested field set is to insert the fields directly. Nested fields are tricky - there are a couple of approaches "out there", in the internet. The following is the one I use.

    In this variation, the outer-most field is inserted with placeholder text for the inner field code(s). The placeholder text is the field code with typed brackets (not the Ctrl+F9 kind).

    The outer field is sent to the Function GenerateNestedField along with the placeholder string. The function locates the placeholder in the field's code and inserts the real field in its place.

    I had to modify my standard code to work with the fact that you're inserting a MailMergeField for the If field. It's necessary to convert the MailMergeField to a regular Word.Field which I do by selecting the inserted field, then taking the first Field in the Fields collection.

    Sub IfPlusMergeField()
        Dim doc As word.Document
        Dim sFieldCode As String, sFieldName As String
        Dim fldMerge As word.MailMergeField
        Dim fldIf As word.Field
    
        Set doc = ActiveDocument
        sFieldName = dt.FieldName
        sFieldCode = "{Mergefield " & sFieldName & "}"
        Set fldMerge = doc.MailMerge.Fields.AddIf(Range:=Selection.Range, _
                       MERGEFIELD:=sFieldName, Comparison:=wdMergeIfGreaterThan, _
                       CompareTo:="30", TrueText:=sFieldCode, _
                       FalseText:="0")
        fldMerge.Select
        Set fldIf = Selection.Fields(1)
        Debug.Print GenerateNestedField(fldIf, sFieldCode)
    End Sub
    
    'Returns the changed field code
    Function GenerateNestedField(fldOuter As word.Field, _
                                 sPlaceholder As String) As String
    
        Dim rngFld As word.Range, doc As word.Document
        Dim bFound As Boolean
        Dim sFieldCode As String
    
        Set doc = fldOuter.Parent
    
        Set rngFld = fldOuter.code
        rngFld.TextRetrievalMode.IncludeFieldCodes = True
        bFound = rngFld.Find.Execute(findText:=sPlaceholder)
        'Get the field code from the placeholder by removing the { }
        sFieldCode = Mid(sPlaceholder, 2, Len(sPlaceholder) - 2)
        If bFound Then
            doc.Fields.Add rngFld, word.WdFieldType.wdFieldEmpty, sFieldCode, False
        End If
        'Debug.Print fldOuter.code
    
        GenerateNestedField = fldOuter.code
    End Function
    

    0 讨论(0)
提交回复
热议问题