In the image below, the error is neglected by declaring the On Error Resume Next statement, which replicates the Try Catch statement.
Download Practice Workbook
Download the Excel Workbook file.
What Is the Excel VBA Try Catch?
There is no explicit “try-catch” statement, you can replicate it using the On Error Resume Next or the On Error GoTo statement in Excel VBA.
VBA Try-Catch Error:
In the above image, there is an overflow in the marked line that leads to a Run-Time error ’11’. Because of that error, the code is unable to display the result of rest two lines.
Unlike other computer programming languages, VBA doesn’t have a Catch statement.There are 3 alternatives:
- On Error Resume Next statement to get rid of errors.
- On Error GoTo 0 statement to find errors.
- On Error GoTo [Label] statement to handle compile errors.
To run a VBA code, you need to open the code window.
Example 1 – On Error Resume Next
There is an overflow in the highlighted line that leads to an error. If you write On Error Resume Next before the formula, the code skips the line with the error and continues. In the Immediate window, we get 2 outputs neglecting the error value.
Example 2 – On Error GoTo 0
The On Error GoTo 0 statement figures out the error code and error name. The above image shows 2 results neglecting the value of q. If you use On Error GoTo 0, the code stops executing and shows the error in a message box.
Example 3 – On Error GoTo [Label]
The On Error GoTo [Label] statement moves to its label destination if it figures out any error in the code. Here, the code goes to label(Err:) as it finds an error(0/0). There are 3 results instead of 7 in the Immediate window.
Get FREE Advanced Excel Exercises with Solutions!