宏从Excel数据运行Word邮件合并

时间:2014-09-02 15:14:52

标签: excel vba excel-vba

我有一些VBA代码,理论上应该选择活动工作簿并使用数据打开Word文档并保持打开邮件合并文档以供审阅/保存。

它工作了一次,但现在它没有拿起打开的电子表格,而是打开一个“选择表”窗口,其中唯一的选项是没有数据的XLSTART.xls电子表格。 但是,它会打开我想要使用的正确Word文档。

是否可以建议我需要修改代码以便它获取活动工作簿?

Sub Mailmerge()
    Dim wd As Object
    Dim wdocSource As Object
    Application.DisplayAlerts = False
     ' Word constants
    Const wdFormLetters = 0, wdOpenFormatAuto = 0
    Const wdSendToNewDocument = 0, wdDefaultFirstRecord = 1, wdDefaultLastRecord = -16
    Dim strWorkbookName As String
    On Error Resume Next
    Set wd = GetObject(, "Word.Application")
    If wd Is Nothing Then
        Set wd = CreateObject("Word.Application")
    End If
    On Error GoTo 0
    Set wdocSource = wd.Documents.Open("File Name for Mail Merge doc, this bit works when not redacted!")
    strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
    wdocSource.Mailmerge.MainDocumentType = wdFormLetters
    wdocSource.Mailmerge.OpenDataSource _
    Name:=strWorkbookName, _
    AddToRecentFiles:=True, _
    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
    wd.Visible = True
    wdocSource.Close SaveChanges:=False
    Set wdocSource = Nothing
    Set wd = Nothing
End Sub

0 个答案:

没有答案