Search code examples
vbams-wordmailmerge

VBA MS Word - Insert all mail merge fields into Word doc at once


Currently MS Word only allows for the insertion of 1 mail merge field at a time. I am looking for a VBA code that would allow me to insert all merge fields into a Word doc at once and/or a code that would input a mail merge field where the name of the same mail merge text appears in the doc.

For the second possibility I have found the following code that allows the user to convert text that matches a mail merge name into a mail merge field one at a time ( http://apsona.com/blog/how-to-quickly-create-merge-fields-in-word/ ). I am dealing with a data source that contains thousands of mail merge fields so ideally I would want to do this for all of them at once or create a loop or something similar.

Sub MakeMergeField()

Selection.Copy
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"MERGEFIELD """ + Selection.Text + """, PreserveFormatting:=True"

End Sub

Solution

  • There's no functionality in Word to insert all merge fields at once, so you need to insert them individually, in a loop.

    The following does that, separating each merge field by a space.

    (Note: Normally, when you insert something in Word, the target Range encompasses what was inserted - not so with merge fields. That's why Range.Start is moved to the end of the document after each insertion, before adding a space to it. Then the Range needs to be "collapsed" beyond that space before doing the next insertion.)

    Sub InsertAllMergeFields()
        Dim doc As word.Document
        Dim rng As word.Range
        Dim mm As word.MailMergeDataField
    
        Set doc = ActiveDocument
        Set rng = doc.content
        If doc.MailMerge.MainDocumentType <> wdNotAMergeDocument Then
            For Each mm In doc.MailMerge.DataSource.DataFields
                doc.MailMerge.Fields.Add rng, mm.NAME
                rng.Start = doc.content.End
                rng.InsertAfter " "
                rng.Collapse wdCollapseEnd
            Next
        End If
    End Sub