我目前正在开发一个创建邮件合并的Excel电子表格,然后将邮件合并拆分为组件文件,一旦程序启动就不需要任何干预。
我遇到的问题是,在邮件合并之后,wdApplication焦点会移回到原始word文档,我无法弄清楚如何使邮件合并活动文档,或者将变量设置为新的邮件合并,以便我可以在那里进行操作。
这是我目前的代码:
Dim wdApp As New Word.Application, wdDoc As Word.Document
Dim strWorkbookName As String: strWorkbookName = ThisWorkbook.FullName
Dim sections As Integer
Dim fileName As String
With wdApp
.DisplayAlerts = wdAlertsNone
Set wdDoc = .Documents.Open(ThisWorkbook.Path & "\Potential Template.docx", ConfirmConversions:=False, ReadOnly:=True, AddToRecentFiles:=False)
With wdDoc
With .MailMerge
.MainDocumentType = wdFormLetters
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
.OpenDataSource Name:=strWorkbookName, ReadOnly:=True, _
LinkToSource:=False, AddToRecentFiles:=False, _
Format:=wdOpenFormatAuto, _
Connection:="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=strWorkbookName;" & _
"Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
SQLStatement:="SELECT * FROM `'Final Data Set$'`", _
SubType:=wdMergeSubTypeAccess
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute
.MainDocumentType = wdNotAMergeDocument
End With
.Close SaveChanges:=wdDoNotSaveChanges
End With
.Browser.Target = wdBrowseSection
For i = 1 To ((ActiveDocument.sections.Count) - 1)
ActiveDocument.Bookmarks("\Section").Range.Copy
Documents.Add
Selection.Paste
Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend
Selection.Delete Unit:=wdCharacter, Count:=1
fileName = filePath & Worksheets("Final Data Set").Range(Cells(i + 1, 4)).value
ActiveDocument.SaveAs (fileName)
ActiveDocument.Close
.Browser.Next
Next i
.DisplayAlerts = wdAlertsAll
.Visible = True
.Quit SaveChanges:=wdDoNotSaveChanges
End With
答案 0 :(得分:0)
您需要查看Word文档的MailMergeAfterMerge事件。
但是,为了能够处理事件,您需要在模块级别将Document声明为Private WithEvents wdDoc As Word.Document
。
Private Sub wdDoc_MailMergeAfterMerge(Doc As Document, DocResult As Document)
End Sub
在邮件合并中的所有记录成功合并后发生。
Name Data-Type Description
Doc Document The mail merge main document.
DocResult Document The document created from the mail merge
注意WithEvents
不能在标准模块中声明。