【问题标题】:Runtime Error 424 on Generation of Mail Merge生成邮件合并时出现运行时错误 424
【发布时间】: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")

提前致谢!

【问题讨论】:

    标签: vba excel mailmerge


    【解决方案1】:

    wdApp 似乎设置不正确。尝试使用 F8 进行调试并在该变量上添加监视以查看它是否已设置。

    我使用 CreateObject 而不是 GetObject 方法,以确保创建对象并且它对我有用。尝试修改此代码:

    Set wdApp = CreateObject("Word.Application")
    wdApp.Visible = True
    Set wordfile = wdApp.Documents.Open("path to the file")
    ' dispose of the object
    Set wdApp = Nothing
    

    【讨论】:

    • 感谢 Michael 的帮助 - 使用 createObject 和 Moosli 下面的代码,没有更多问题。
    【解决方案2】:

    我认为问题出在这里,找不到对象,因为没有打开 Word 实例。 我喜欢你的做法以及检查 wdApp 是否为空的方式。

    Set wdApp = GetObject(, "word.application")
       If wdApp Is Nothing Then
          Set wdApp = GetObject("[LOCATION OF WORD MAIL MERGE DOC]", "word.application")
       end if
    

    现在您只需要再次检查 wdApp 变量是否为空。如果是,只需创建一个 Word 实例就可以了。

    所以我会在上面看到的代码之后添加这行代码。

    if wdApp is Nothing Then
       Set wdApp = CreateObject("Word.Application")
    end if
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多