Detecting if an object has been disconnected from its clients

I am having a problem with automating an Excel file. The VBA script in Excel first opens a Word application and a Word document:

    Dim wordApp As Object
    Set wordApp = CreateObject("Word.Application")

    vPath = Application.ActiveWorkbook.Path
    Set wordDoc = wordApp.Documents.Open(vPath & "\test.doc")

And then I call the subroutine in the Word document, passing some data from the Excel file:

    Call wordApp.Run("StartWithData", variable1, variable2)

If Excel detects an error in this routine, I will close the Word document and Word application from Excel in the shortcut that I call Err1:

    On Error Goto Err1
    'all the code from above
    Exit Sub

    Err1:
    wordDoc.Close wdCloseWithoutSaving
    wordApp.Quit SaveChanges:=wdDoNotSaveChanges
    Set wordDoc = Nothing
    Set wordApp = Nothing

This works fine under normal circumstances; however, if the Word document or application is closed before the label is executed Err1(for example, the user manually closes the document), I get the following error:

Runtime error '-2147417848 (80010108)':
Automation error The called object is disconnected from its clients.

, wordApp / wordDoc - , ( Nothing).

, : , , on error resume next?

Such as:

    If Not isDisconnected(wordDoc) Then
    wordDoc.Close wdCloseWithoutSaving
    End If

    If Not isDisconnected(wordApp) Then
    wordApp.Quit SaveChanges:=wdDoNotSaveChanges
    End If

1:

omegastripes, , , (wordDoc) . Word (wordApp) , :

'462':

+4
1

:

Sub Test()
    Dim wordApp As Object
    Dim wordWnd As Object
    Dim wordDoc As Object

    Set wordApp = CreateObject("Word.Application")
    Set wordWnd = wordApp.Windows ' choose any object property as indicator
    wordApp.Visible = True ' debug
    Set wordDoc = wordApp.Documents.Open(Application.ActiveWorkbook.Path & "\test.doc")
    MsgBox IsObjectDisconnected(wordWnd) ' False with opened document
    wordDoc.Close
    MsgBox IsObjectDisconnected(wordWnd) ' False with closed document
    wordApp.Quit ' disconnection
    MsgBox IsObjectDisconnected(wordWnd) ' True with quited application
End Sub

Function IsObjectDisconnected(objSample As Object) As Boolean
    On Error Resume Next
    Do
        IsObjectDisconnected = TypeName(objSample) = "Object"
        If Err = 0 Then Exit Function
        DoEvents
        Err.Clear
    Loop
End Function

, , Word, .Documents, .Windows, .RecentFiles .., , 14: , Word . Application Excel.

TypeName() OERN, , , , . , Application .Windows.

+3

Source: https://habr.com/ru/post/1615821/


All Articles