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