Excel VBA Run Time error the second times

Viewed 48

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." I don't see any unqualified object or method or property in my code.

1 Answers

I think it's likely that MS Word is already running. 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.

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

Related