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

房东的猫 提交于 2019-12-11 05:37:36

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/50031198/vba-ms-word-insert-all-mail-merge-fields-into-word-doc-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!