【问题标题】:MailMerge Excel to Word individual filesMailMerge Excel 到 Word 单个文件
【发布时间】:2013-10-05 20:25:22
【问题描述】:

我正在尝试创建以下内容:

在 Excel 中存储数据以创建邮件合并,并在单个 pdf 文件中输出,文件名为“字母 + 名称”来自数据。

需要使用 Excel 中的“创建字母”按钮来创建单个文件。

我快到了,我唯一的问题是我创建了单独的 pdf 文件,但所有文件都具有与第 1 行相同的数据。

如何创建具有单独数据的每个文件的单独文件?

 Sub RunMailMerge()

 Dim wdOutputName, wdInputName, PDFFileName As String
 Dim x As Integer
 Dim nRows As Integer

wdInputName = ThisWorkbook.Path & "\Templates\LetterExample.docx"
Const wdFormLetters = 0, wdOpenFormatAuto = 0
Const wdSendToNewDocument = 0, wdDefaultFirstRecord = 1, wdDefaultLastRecord = 3

'This will get you the number of records "-1" accounts for header
nRows = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row - 1

' open the mail merge layout file
Dim wdDoc As Object

Set wdDoc = GetObject(wdInputName, "Word.document")

wdDoc.Application.Visible = False


For x = 1 To nRows

With wdDoc.MailMerge
     .MainDocumentType = wdFormLetters
     .Destination = wdSendToNewDocument
     .SuppressBlankLines = True
      With .DataSource
        .FirstRecord = wdDefaultFirstRecord
        .LastRecord = wdDefaultLastRecord
    End With
     .Execute Pause:=False
End With

' show and save output file

'cells(x+1,2)references the first cells starting in row 2 and increasing by 1 row with each loop
PDFFileName = ThisWorkbook.Path & "\Letter - " & Sheets(1).Cells(x + 1, 2) & ".pdf"

wdDoc.Application.Visible = False
wdDoc.ExportAsFixedFormat PDFFileName, 17   ' This line saves a .pdf-version of the mail merge

Next x

' cleanup
wdDoc.Close SaveChanges:=False
Set wdDoc = Nothing

MsgBox "Your pdf('s) has now been saved!"

End Sub

【问题讨论】:

    标签: excel vba ms-word mailmerge


    【解决方案1】:

    尝试将您的邮件合并移到 for 循环之上,然后逐步遍历 for 循环内的每个记录集:

    With wdDoc.MailMerge
         .MainDocumentType = wdFormLetters
         .Destination = wdSendToNewDocument
         .SuppressBlankLines = True
          With .DataSource
            .FirstRecord = wdDefaultFirstRecord
            .LastRecord = wdDefaultLastRecord
        End With
         .Execute Pause:=False
    End With
    
    For x = 1 To nRows
      With ActiveDocument.MailMerge.DataSource 
         .ActiveRecord = x 
         If .ActiveRecord > .LastRecord Then Exit For
      End with
    
      '.... rest of your for loop
    

    【讨论】:

    • 您好 Portland Runner,我尝试了您建议的方法,但收到运行时错误“424”:以下行需要对象:使用 ActiveDocument.MailMerge.DataSource。我需要在这一行中更改什么?
    • 尝试将 activedocument 更改为 wdDoc
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2020-04-26
    • 2017-04-08
    相关资源
    最近更新 更多