1

In Excel VBA, I open a Word app and a doc inside. I want to make sure the doc and Word are closed at the end, even if there was an error.

I created an error handler with On Error GoTo ErrorHandler, that works. But there objDoc.Close fails when the doc was not opened (Runtime error 424), and the Sub is aborted before objWord.Quit although I called On Error Resume Next.

Why does On Error Resume Next not work there?

(In VBA options, Error Trapping is set to "Break on Unhandled Errors".)

Sub test()
    On Error GoTo ErrorHandler
    ' Open doc in Word
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = False
    Set objDoc = objWord.Documents.Open("not a valid doc.docx")

    ....

    ' Save and exit
    objDoc.Save
    objDoc.Close
    objWord.Quit
    Exit Sub

ErrorHandler:
    MsgBox "Error " & Err.Number & vbLf & Err.Description
    On Error Resume Next
    ' Exit
    objDoc.Close SaveChanges:=False
    objWord.Quit
    On Error GoTo 0
End Sub
Axel Williot
  • 485
  • 6
  • 13

1 Answers1

5

Here's how I would do it, like @Comintern says

Sub test()
    Dim objWord As Object
    Dim objDoc As Object

    On Error GoTo ErrorHandler
    ' Open doc in Word
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = False
    Set objDoc = objWord.Documents.Open("not a valid doc.docx")




ErrExit:
    On Error Resume Next
    objDoc.Save
    objDoc.Close
    objWord.Quit
    Exit Sub

ErrorHandler:
    MsgBox "Error " & Err.Number & vbLf & Err.Description
    Resume ErrExit
End Sub

That Resume statement gets you out of the error state and allows you to reset an error trap.

Dick Kusleika
  • 32,673
  • 4
  • 52
  • 73
  • 2
    Upvoted; I would only add that the variables should be explicitly declared, and the double-dot referencing of `objWord.Documents` is leaking the implicit collection object, which means OP probably has a bunch of WINWORD.EXE ghost processes in their task manager (see my deleted answer) – Mathieu Guindon Feb 07 '19 at 15:41