2013-10-05 47 views
1

我试图创建以下文件:邮件合并的Excel到Word单个文件

在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 

回答

0

尝试移动上面的你的邮件合并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 
+0

嗨波特兰亚军,我想你建议的方法,但我收到一个运行时错误'424':对象需要在以下行上:使用ActiveDocument.MailMerge.DataSource。我需要改变这一行吗? –

+0

尝试将activedocument更改为wdDoc –