0

首先是我的代码。

Sub RunMerge()
' Word constants

Dim wd As Object
Dim wdocSource As Object

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(ThisWorkbook.Path & "\AAFCAAC-#4077508-v1-AAFC-FFPB-COPE-SATD-_AgriInnovation_Draft_Survey_Instructions_189318.doc")

strWorkbookName = ThisWorkbook.Path & "\" & "MD.xlsm"

wdocSource.MailMerge.MainDocumentType = wdFormLetters

wdocSource.MailMerge.OpenDataSource _
        Name:=strWorkbookName, _
        AddToRecentFiles:=False, _
        Revert:=False, _
        Format:=wdOpenFormatAuto, _
        Connection:="Data Source=" & strWorkbookName, _
        SQLStatement:="SELECT * FROM 'Mail Merge Data$'"

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

我正在尝试将邮件合并从 excel 到 word。我的问题(我相信)是 SQLStatement:="SELECT * FROM 'Mail Merge Data$'" 因为当我运行我的代码时,excel 进入了等待单词的边缘。当我进入我的任务管理器时,我看到选择一张桌子时卡住了。表格选择菜单中没有选项,指定的工作簿只是我的工作簿的路径,末尾附加了 .xls。如果我删除 SQLStatement 行,会发生同样的事情,但选择表中填充了工作簿中的工作表和名称范围。我希望这是我的一个小错误或错字。

4

1 回答 1

3

我认为问题在于您删除了您的情况所需的额外引号。您的 SQL 语句应该看起来像:

SQLStatement:="SELECT * FROM `'Mail Merge Data$'`"

您也可以尝试使用以下代码:

SQLStatement:="SELECT * FROM [Mail Merge Data$]"
于 2013-05-29T19:17:08.780 回答