There are many reasons why error occurs in VBA. To identify the error, you can print the error on screen using the following codes.


‘Main Macro is located here.

Exit Sub

” – – – – – – – – – – – – – – – – – – – – – – – – – – – –
ErrorHandler:

vtMessage = “Program Error”
vtMessage = vtMessage & _
Chr(10) & _
Chr(10) & “Error Number: ” & Err & _
Chr(10) & “Error Description: ” & Error()

MsgBox vtMessage, vbInformation, ctByg

End Sub

To direct the macro to run these codes on error, you can write the statement:

On Error Goto ErrorHandler

This will make sure that the macro will be direct to the ErrorHandler labelled ErrorHandler:

The whole set of codes to handle error must be after the statement Exit Sub to ensure that these codes are not run under normal circumstances. Note that it is not after END SUB but it is after EXIT SUB.

Leave a Reply