【发布时间】:2017-08-17 08:51:19
【问题描述】:
我是 VBA 的新手,并且已经设法从一个非常有用的堆栈溢出者那里编写了一个代码,以从 excel 中的宏按钮(与数据库相同的文档)生成邮件合并。
宏大部分时间都可以无缝运行,但是我经常收到运行时错误 424(需要对象)消息。再次运行宏而不更改任何内容总是有效的,所以我认为问题与定义我想要定位的 word 文档有关。
我的代码是:
Sub Letter_Generator()
Calculate
MsgBox "Please Select the Word Document (on below taskbar) & select ok to all options."
Dim wdApp As Word.Application
On Error Resume Next
' open the mail merge layout file
Dim wdDoc As Word.Document
' Error handling
Set wdApp = GetObject(, "word.application")
If wdApp Is Nothing Then
Set wdApp = GetObject("[LOCATION OF WORD MAIL MERGE DOC]", "word.application") ' End If
On Error GoTo 0
With wdApp
' Set wdDoc = .Documents.Open
Set wdDoc = .Documents.Open(Filename:="LOCATION OF WORD MAIL MERGE DOC]") '
wdDoc.Application.Visible = True
With wdDoc.MailMerge
.OpenDataSource Name:="[LOCATION OF EXCEL DATABASE]"
.MainDocumentType = wdFormLetters
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
.Execute Pause:=False
End With
wdDoc.Application.Visible = True
.Selection.WholeStory
.Selection.Fields.Update
wdDoc.Close SaveChanges:=False
Set wdDoc = Nothing
End With
End Sub
对于消除错误的任何帮助,我将不胜感激 - 正如我所说,我可以通过运行宏两次来很好地运行合并,但现在宁愿消除任何问题!
调试显示这部分是罪魁祸首-
Set wdDoc = .Documents.Open(Filename:="K:\Team London & South East\Prop Letter\Prop Letter Bare Bones2.docx")
提前致谢!
【问题讨论】: