简体   繁体   English

Excel VBA 第二次运行时间错误

[英]Excel VBA Run Time error the second times

Can anyone say me why the second time I run the macro I receive a runtime error?谁能告诉我为什么我第二次运行宏时收到运行时错误?

Dim wApp as Object
Dim wDoc as Object
Set wApp = CreateObject("word.Application")
Set wDoc = wApp.Documents.Add(Template:="Test.dotm", Visible:=True)

On Microsoft support: "Visual Basic has established a reference to Word due to a line of code that calls a Word object, method, or property without qualifying it with a Word object variable. Visual Basic does not release this reference until you end the program. This errant reference interferes with automation code when the code is run more than once."在 Microsoft 支持上:“Visual Basic 已建立对 Word 的引用,因为一行代码调用了 Word object、方法或属性,而没有使用 Word object 变量对其进行限定。Visual Basic 不会释放此引用,直到您结束程序. 当代码运行不止一次时,这个错误的引用会干扰自动化代码。” I don't see any unqualified object or method or property in my code.我在我的代码中没有看到任何不合格的 object 或方法或属性。

I think it's likely that MS Word is already running.我认为 MS Word 很可能已经在运行。 So here are a couple of routines from my library to check if MS Word is already running or not, and to make a connection to the process.因此,这里有几个来自我的库的例程,用于检查 MS Word 是否已经在运行,并与该进程建立连接。

Option Explicit

Public Function MSWordIsRunning() As Boolean
    '--- quick check to see if an instance of MS Word is running
    Dim msApp As Object
    On Error Resume Next
    Set msApp = GetObject(, "Word.Application")
    If Err > 0 Then
        '--- not running
        MSWordIsRunning = False
    Else
        '--- running
        MSWordIsRunning = True
    End If
End Function

Public Function AttachToMSWordApplication() As Word.Application
    '--- finds an existing and running instance of MS Word, or starts
    '    the application if one is not already running
    Dim msApp As Word.Application
    On Error Resume Next
    Set msApp = GetObject(, "Word.Application")
    If Err > 0 Then
        '--- we have to start one
        '    an exception will be raised if the application is not installed
        Set msApp = CreateObject("Word.Application")
    End If
    Set AttachToMSWordApplication = msApp
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM