pascal sautot
pascal sautot

Reputation: 405

Excel VBA run time error is raised by the IDE while there is an error handler set

I have a weird error reported by a user of a VBA based application
and I wonder how this just possible that an error is raised by the VBA IDE considreing the line above is an error handler.

The code is the following. It creates a form of class frmCfgPrjctTm. I used to have some automation errors once in a while with weird message from the VBA IDE.

Run-time error '-2147418105 (800100007)': Automation error The object invoked has disconnected from its clients. I use Excel 2016 32 bits on windows 7.

To work around the problem I had to implement a retry strategy to create the form. This explains the retry loop.

The error is raised on line mForm.Show vbModeless. The error handler is set with instruction On Error GoTo ErrorHandler the line just before!

Private mForm As frmCfgPrjctTm
''
' U_CfgPrjctTm_OnOpen
Public Sub U_CfgPrjctTm_OnOpen()
        Dim iRetry As Integer
        iRetry = 0
        If (mForm Is Nothing) Then
ErrorExit:
            If (iRetry > 1) Then
                Call U_UnlockTeam
                GoTo ExitSub
            End If
            iRetry = iRetry + 1
            Set mForm = New frmCfgPrjctTm
        End If
        On Error GoTo ErrorHandler
        '>>>>>> the error occurs after this comment
        mForm.Show vbModeless
ExitSub:
Exit Sub
ErrorHandler:
    Debug.Print "***** Error trapped in U_CfgPrjctTm_OnOpen *****"
    GoTo ErrorExit
End Sub

this post raises 2 questions but I am seeking for help or sharing for the following :

why an error is raised by the IDE while there is an error handler set ?

Upvotes: 0

Views: 292

Answers (1)

Storax
Storax

Reputation: 12167

The answer to your question "why an error is raised by the IDE while there is an error handler set ?" is that you use error handling in a wrong way. Look at the following example

 Option Explicit

    Sub TestErrH()

Dim i As Long

    i = 42

ErrorExit:

    On Error GoTo ErrorHandler
    Debug.Print 42 / i
    Debug.Print 1 / 0

    Exit Sub

ErrorHandler:
    i = 0
    GoTo ErrorExit

End Sub

The error handler will raise in the line Debug.print 1/0 and then the error handler will set i = 0 and jump back to the line debug.print 42/i. At that time the error handling is in your hands. You have to make sure the code is fail safe. The error handler will not again jump to the label ErrorHandler instead a run time error will pop up.

Upvotes: 1

Related Questions