Excel VBA – Try Catch – Errors
This article will demonstrate how to use VBA to Try Catch Errors.
In most programming languages, you can use the syntax Try…Catch…End Try to prevent errors from occurring. The code literally tries to run and if it encounters and error, it jumps down to the catch line where the error can be documented and retuned to the user. VBA does not use the Try…Catch…End Try syntax but we can mimic this syntax by using the On Error GoTo syntax instead.
On Error GoTo
The On Error GoTo statement in VBA will force our code to move to a specific line of code if an error occurs.
Sub RenameSheet ()
On Error GoTo eh
ActiveSheet.Name = "Sheet1"
Exit Sub
eh:
MsgBox Err.Description
End Sub
In the above example, we have put added an error trap where we direct the code to move to the error handler if an error occurs. We then try to rename the sheet to be Sheet1. If we are in Sheet2 for example, and try to rename it to Sheet1 BUT Sheet1 already exists, then the error will occur and the code will jump down to the error handler.
However, if there is no sheet 1 in the workbook, then the code will run perfectly and as there is an Exit Sub BEFORE the error handler, the error handler code will not be reached.