【发布时间】:2019-01-05 01:51:24
【问题描述】:
这里是场景。我在 Excel 2016 中使用 VBA 来启动与 Word 的邮件合并。合并的数据源是当前 Excel 文档中的电子表格。该例程为数据集的每次迭代生成一个单独的合并文档。
当我遍历数据集时,会创建一个新的合并文档并保存为 PDF 文档。
问题 #1:
循环时的例程会创建单独的合并文档。每个合并文档都是可见的,所以如果我遍历 5 个数据集,我会得到 5 个打开的合并文档,每个都有适当的数据集值。但是当另存为 PDF 时,它会一遍又一遍地保存第一个合并文档。
在我的代码中,“另存为 PDF”部分会根据数据集中的字段生成一个唯一的文件名,并且可以正常工作。每个保存的 PDF 都有相应的文件名,但实际文件是第一个反复合并的文档。
如何获得将第一个合并文档保存为 PDF 的例程,然后继续进行下一次迭代?
问题 #2:
当例程循环并创建独立的合并文档时,我该如何关闭新创建的单词合并文档?
现有代码:
z = 0
For z = 0 To xCount - 1
lb2_selected = "''" + lb2_array(0, z) + "''"
addr_query = "sp_address_filter '" + lb2_selected + "','" + lb1_selected + "','','" + lb3_selected + "','',''"
'MsgBox (addr_query)
Set rs = conn.Execute(addr_query)
'Clear any existing data from Sheet2
Worksheets("Sheet2").Range("A1:Z10000").Clear
'Load new iteration of data into Sheet2
With rs
For h = 1 To .Fields.Count
Sheet2.Cells(1, h) = .Fields(h - 1).Name
Sheet2.Cells(1, h).Font.Bold = True
Next h
End With
If Not rs.EOF Then
Sheets(2).Range("A2").CopyFromRecordset rs
End If
rs.Close
'Set value for filename
lb2_array_value = lb2_array(1, z)
Dim wd As Object
Dim wdocSource As Object
Dim strWorkbookName As String
Set wd = CreateObject("Word.Application")
Set wdocSource = wd.Documents.Open("c:\users\john\documents\LabelPage3.docx")
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
wdocSource.MailMerge.MainDocumentType = wdFormLetters
wdocSource.MailMerge.OpenDataSource _
Name:=strWorkbookName, _
AddToRecentFiles:=False, _
Revert:=False, _
Format:=wdOpenFormatAuto, _
Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
SQLStatement:="SELECT * FROM `Sheet2$`"
With wdocSource.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
"C:\users\john\documents\labels\" + lb2_array_value + ".pdf", _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
wd.Visible = True
wdocSource.Close SaveChanges:=False
Set wdocSource = Nothing
Set wd = Nothing
Next z
【问题讨论】:
-
对于问题#2,文档关闭和对象的最后释放不关闭文档?
-
正确。生成的合并文档(循环的每次迭代一个)保持打开状态。
-
奇数。我今天的帖子和冻糕帖子都不见了。那吹。 :(
-
然而,并不是所有的都丢失了。经过一番修改,我发现通过修改:“ActiveDocument.ExportAsFixedFormat...”到“wd.ActiveDocument.ExportAsFixedFormat...”这会导致循环的每次迭代都会为合并文档创建一个单独的PDF。
-
啊……这就解释了。谢谢你让我知道。数据源在循环时正在更新。请参阅我以前的帖子,因为我相信我可以正常工作。 :)
标签: excel vba for-loop pdf mailmerge