Dozens
Dozens

Reputation: 145

VBA - goto excel error message in error handling if

I wanted to write the error handling for vba, which after directing to the error handling will first check for a specific error and if there is no match, it will show the error message as according to Excel.

Here is my code:

On Error GoTo ErrorHandl

ErrorHandl:
If Err.Number = 13 Then
  MsgBox "Do that …", vbCritical
  Exit Sub
Else
??????

What could I write in the place of questions marks, so that if error number is different than 13 then, excel will show me the other error that is currently occurring?

Upvotes: 0

Views: 842

Answers (2)

Vityata
Vityata

Reputation: 43585

This is a possible way to get custom errors with Select Case:. If the error is number 11 (Division by 0), then it gives a customized MsgBox. Othewise it gives a standard one with the Err.Number and Err.Description, based on the current language of the system (Mine is German):

enter image description here

The code:

Sub TestMe()

    On Error GoTo TestMe_Error

    Debug.Print 5 / 0

    On Error GoTo 0
    Exit Sub

TestMe_Error:

    Select Case Err.Number
    Case 11:
        MsgBox "Division by null is not allowed on this planet!"
    Case Else:
        MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure TestMe."
    End Select

End Sub

And if you need a multipurpose Error-Handler, this is the code:

Sub TestMe()

    On Error GoTo TestMe_Error

    Debug.Print 5 / 0

    On Error GoTo 0
    Exit Sub

TestMe_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure TestMe."

End Sub

Upvotes: 1

Tim Stack
Tim Stack

Reputation: 3248

The code you wrote now is error number specific. You could also write a general error handler

Sub test()
On error GoTo Errorhandler

 '''
 'Code
 '''

Exit Sub
Errorhandler:
MSgbox "Warning: fatal error occured." & vbCr & vbCr "Error message:" & vbCr & Err.Description, vbcritical, "Error"
End Sub

This will, regardless of which error occured, display a message box warning the user of a fatal error followed by the error message as displayed in VBE.

Of course, you could also specify the error code instead of making it general

Upvotes: 0

Related Questions