我有一个设置一个Excel工作簿和一个Word文档,它创建了一组客户交付说明。注释的数据在Excel簿中,Word文档使用Merge创建可打印的文档。该进程由Excel端的VBA宏控制,该宏启动Word,打开Word文档,然后在Word文档中调用VBA宏,该宏执行实际的邮件合并工作。
我每周使用这一周大约一年,它的工作非常好。但上周突然间,单词宏开始抛出错误4605!现在,在我运行它的两台Windows机器上,这种情况都会持续发生。
为了寻找答案,我了解到4605是一个非常常见的错误,表明了宏中的语句无法执行的任何原因。在我的例子中,语句是MailMerge.OpenDataSource,给出的原因是“因为宏正在运行”。请参阅下面的代码。
我不认为OpenDataSource的参数有什么问题,我试图以各种方式修改它们。看来,由于某种原因,这一呼吁是被禁止的。我还试图在违规调用之前引入延迟,以防有一些隐藏的宏需要首先完成。在调用了宏之后,我尝试过暂停Excel宏。但没有运气。
Public Sub PopulatePrintExit(odbcFile As String, pdfFile As String)
On Error GoTo closeThis
With ThisDocument.MailMerge
.OpenDataSource Name:= _
odbcFile, ConfirmConversions:=False, _
ReadOnly:=True, LinkToSource:=True, AddToRecentFiles:=False, _
Revert:=False, Format:=wdOpenFormatAuto, _
Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=OdbcFile;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Typ", _
SQLStatement:="SELECT * FROM `Fraktsedelsdata$` WHERE (`Aviseringsnr` IS NOT null And `Aviseringsnr` <> '')"
.Destination = wdSendToNewDocument
On Error GoTo closeAll
.Execute
End With
...
发布于 2022-09-27 10:18:33
解决了!
我完全省略了宏这个词,而是将语句移到Excel宏中。那就成功了!
我还是很好奇为什么会发生这种事.
发布于 2022-11-22 22:26:38
当然@MohammedAhsan!以下是我在Excel宏中所做的工作:
Dim wordapp As Word.Application
Dim worddoc As Word.Document
' Open Word...
Set wordapp = CreateObject("Word.Application")
'... in the background
wordapp.Visible = False
' Open the template document
Set worddoc = wordapp.Documents.Open(Filename:="path to Word template", Revert:=True, ConfirmConversions:=False, _
ReadOnly:=True, AddToRecentFiles:=False)
' Execute mail merge, with data from this workbook
With worddoc.MailMerge
.OpenDataSource Name:= _
WorkbookPath() & ThisWorkbook.Name, ConfirmConversions:=False, _
ReadOnly:=True, LinkToSource:=True, AddToRecentFiles:=False, _
Revert:=False, Format:=wdOpenFormatAuto, _
Connection:= _
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=OdbcFile;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Typ", _
SQLStatement:="SELECT * FROM `Fraktsedelsdata$` WHERE (`Butik` = 'Ja' AND `Antal kartonger` > 0)"
.Destination = wdSendToNewDocument
.Execute
End With
' The created merge is now the active document instead of the template,and can be exported or saved
wordapp.ActiveDocument.ExportAsFixedFormat OutputFileName:="the path of the result file", ExportFormat:=wdExportFormatPDF
'Close Word
wordapp.Quit SaveChanges:=wdDoNotSaveChanges
https://stackoverflow.com/questions/73820702
复制相似问题