To call a specific macro when an error occurs in Excel VBA, use the On Error GoTo [Label] statement. This tells VBA to stop executing the current line of code and jump immediately to a designated label (a named line of code) where you can define a custom error-handling routine or call another separate macro to log the error and notify the user. This prevents the application from crashing with a generic "Runtime Error" dialog and allows for a graceful exit or a corrective action.
What You'll Need
- Microsoft Excel installed on a Windows or Mac computer.
- The Developer tab enabled in the Excel Ribbon.
- A basic understanding of how to open the Visual Basic Editor (VBE) using ALT + F11.
- A workbook saved as an Excel Macro-Enabled Workbook (.xlsm).
Step-by-Step
- Open the Visual Basic Editor: Press
ALT + F11on your keyboard to open the VBE window. If you are on a Mac, use the corresponding shortcut or go to the Developer tab and click Visual Basic. - Insert a Module: In the Project Explorer on the left, right-click on your workbook name, select Insert, and then choose Module. This ensures your code is stored in a standard module rather than a sheet-specific object.
- Create the Error Handler Macro: Before writing your main logic, create the macro that will be called when an error occurs. This keeps your code organized. For example:
Sub ErrorLogger() MsgBox "An unexpected error occurred. Please check your data inputs.", vbCritical, "System Error" ' You can add code here to write the error to a log sheet End Sub - Write the Main Procedure: Start your main macro using the
Subkeyword. For example:Sub ProcessData(). - Insert the On Error Statement: At the very beginning of your main procedure, add the line
On Error GoTo ErrorHandler. This tells Excel that if any error occurs from this point forward, it should jump to the label named "ErrorHandler". - Add the Main Logic: Write the code you want to execute. To test your error handler, you can intentionally include a line that causes an error, such as dividing a number by zero:
Range("A1").Value = 10 / 0. - Create the Exit Point: This is the most critical step. You must place an
Exit Substatement immediately before your error handling label. If you omit this, the macro will run the error handler every single time, even if no error occurred. - Define the Error Label: Create the label by typing the name followed by a colon on its own line. For example:
ErrorHandler:. This marks the destination for theGoTocommand. - Call the Error Macro: Under the label, call the separate macro you created in Step 3. Use the syntax
Call ErrorLogger. - Resume or End: After calling the error macro, you can use
Resume Nextto try the next line of code, or simply let the sub end.
Complete Code Example:
Sub ProcessData()
On Error GoTo ErrorHandler
' Main logic starts here
Dim x As Integer
x = 1 / 0 ' This will trigger the error
MsgBox "Process completed successfully!"
Exit Sub
ErrorHandler:
Call ErrorLogger
' Optional: Resume Next to continue after the error
End Sub
Sub ErrorLogger()
MsgBox "A runtime error was detected in ProcessData.", vbExclamation
End Sub
Common Mistakes
One of the most frequent errors is forgetting the Exit Sub statement. Without it, the code flows linearly. Even if the main logic finishes perfectly, the program will continue right into the ErrorHandler: section and trigger the error message. This leads to confusion where users think the macro failed when it actually succeeded.
Another common mistake is creating an "infinite error loop." This happens when the code inside the error handler itself triggers an error. If you have On Error GoTo ErrorHandler active and the code under ErrorHandler: fails, VBA may enter a loop or crash entirely. To prevent this, you can use On Error Resume Next inside the error handler to ignore further issues during the cleanup process.
Users also often forget that On Error GoTo 0 is needed to reset the error handler. If you have a specific block of code where you want a different error behavior, you must clear the previous handler using On Error GoTo 0 before setting a new one. Failure to do so means the original handler remains active for the entire duration of the procedure.
Tips
For professional-grade macros, do not just use a MsgBox in your error handler. Instead, create a hidden worksheet named "ErrorLog". In your ErrorLogger macro, write code that appends the current date, time, the name of the macro that failed, and the Err.Description to the next empty row of that sheet. This allows you to debug issues that occur on a client's machine without having to see it happen in real-time.
Use the Err object to provide more detail. Instead of a generic message, use MsgBox "Error " & Err.Number & ": " & Err.Description. This tells you exactly what went wrong (e.g., "Type Mismatch" or "Subscript out of range"), which makes fixing the bug significantly faster.
If you are dealing with a very long macro, you can use multiple labels. For example, On Error GoTo DataValidationError for the input section and On Error GoTo CalculationError for the math section. This allows you to give the user specific instructions on how to fix the problem based on where it occurred.
Troubleshooting
If the macro does not jump to the error handler and instead shows the standard VBA debug window, check that your label is spelled exactly the same as the name in the GoTo statement. Labels are not case-sensitive, but a typo like ErrorHandler vs Error_Handler will cause the code to fail.
If the error handler runs every time the macro is started, verify that Exit Sub is placed immediately above the label. Ensure there are no empty lines or comments that might accidentally move the Exit Sub inside the error handling block.
If you find that the code is skipping over errors without triggering the handler, check if you have On Error Resume Next written anywhere in your code. Resume Next tells VBA to ignore the error and move to the very next line. If this is active, the GoTo ErrorHandler will be ignored because the error is being suppressed.
If the VBE tells you "Label not defined," it means you have a GoTo [Label] line, but you forgot to create the [Label]: line (with the colon) elsewhere in the same procedure. Remember that labels must be within the same Sub or Function; you cannot GoTo a label located in a different macro.
Frequently Asked Questions
Can I call a macro in a different module for error handling?
Yes. While the ErrorHandler: label must be inside the same procedure, the code under that label can use the Call statement to run any other macro located in any module within the same workbook.
What is the difference between On Error GoTo 0 and On Error Resume Next?
On Error Resume Next tells VBA to ignore errors and keep running the next line. On Error GoTo 0 disables any current custom error handler and returns VBA to its default behavior of showing a runtime error dialog.
Can I use this in a UserForm?
Yes, the logic is identical. Place the On Error GoTo statement at the start of the button click event or the form initialization event to handle crashes during user interaction.
Will this catch syntax errors?
No. On Error only catches "Runtime Errors" (errors that happen while the code is running). It cannot catch "Compile Errors" (syntax mistakes like missing parentheses or misspelled keywords), which must be fixed before the code can run at all.
How do I return to the line that caused the error?
Use the Resume statement without any qualifiers inside your error handler. This tells VBA to attempt to execute the failing line again, which is useful if your error handler fixed the problem (e.g., by creating a missing folder).
Is it better to use On Error GoTo or On Error Resume Next?
On Error GoTo is generally better for critical errors where the process must stop or be logged. On Error Resume Next is better for optional tasks, such as trying to delete a file that might not exist, where the failure doesn't impact the rest of the program.