我能够成功完成(在堆栈交换用户的帮助下)一个宏来自动邮件合并来自excel的word文档。但现在的问题是,除非单词文档打开,否则会出现自动化错误。
现在,我每次只打开word文档来解决它,但我怀疑这是正确的编程方法。
有任何克服此错误的建议吗?我对VBA很新。这是我学生作业的一部分。任何建议或代码更改,以帮助克服此错误?我看了官方msdn文档,不明白一件事。 :'(
错误通常是"自动化错误 - 带有十字标记"或者这个: http://imgur.com/a/zitah 对于这两个错误,到目前为止的解决方案是首先打开word文档然后运行宏。
更新: 我在错误中删除了#34;"部分现在错误是这样的: http://imgur.com/a/epmGR
该计划如下:
Const wdFormLetters = 0, wdOpenFormatAuto = 0
Const wdSendToNewDocument = 0, wdDefaultFirstRecord = 1, wdDefaultLastRecord = -16
Sub RunMerge2()
Dim wd As Object, wdocSource As Object
Dim sh As Worksheet
Dim Lrow As Long, i As Long
Dim cdir As String, client As String, newname As String
Dim sSQL As String
cdir = "C:\Users\Kamlesh\Desktop\"
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(cdir & "\master\installers.docx")
Set sh = ActiveSheet
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
With sh
Lrow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To Lrow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
client = .Cells(i, 1).Value
newname = "Installer Instructions - " & client & ".docx"
wdocSource.MailMerge.MainDocumentType = wdFormLetters
'~~> Sample String
sSQL = "SELECT * FROM `Sheet1$` WHERE [Client Name] = '" & .Range("A" & i).Value & "'"
wdocSource.MailMerge.OpenDataSource Name:=strWorkbookName, _
AddToRecentFiles:=False, Revert:=False, Format:=wdOpenFormatAuto, _
Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
SQLStatement:=sSQL
With wdocSource.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
wd.ActiveDocument.SaveAs cdir & newname
wd.ActiveDocument.Close SaveChanges:=False
End If
Next i
End With
wdocSource.Close SaveChanges:=False
'wd.Quit
Set wdocSource = Nothing
Set wd = Nothing
End Sub
答案 0 :(得分:0)
这一行
Set wdocSource = wd.Documents.Open(cdir & "\master\installers.docx")
应该是
Set wdocSource = wd.Documents.Open(cdir & "master\installers.docx")
和
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
可以替换为
strWorkbookName = ThisWorkbook.FullName
要查找导致错误的代码部分,请在工具&gt;中找到。选项&gt;编辑器选项卡检查所有内容
并在“常规”标签中检查所有内容,然后选择Break in Class Module