How to Use Excel VBA Try Catch – 3 Examples

In the image below, the error is neglected by declaring the On Error Resume Next statement, which replicates the Try Catch statement.

an overview image of Excel VBA try catch

 


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:

Displaying Run-time 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

using of On Error Resume Next statement

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

using On Error GoTo 0 statement

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]

using On Error GoTo [label] statement

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!
MD Tanvir Rahman
MD Tanvir Rahman

MD Tanvir Rahman, BUET graduate in Naval Architecture and Marine Engineering, dedicated over a year to the ExcelDemy project. He is an Excel and VBA Content Developer. Having authored 50+ insightful articles, he actively updates and improves over 80 articles, reflecting his commitment to accuracy and currency, managing day-to-day operations, and analyzing and developing Excel and VBA tutorials. His broad interests encompass Data Analysis, Advanced Excel, VBA Macro, Excel Templates, Excel Automation, and Excel Power Query, showcasing a... Read Full Bio

We will be happy to hear your thoughts

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo