Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA Err Object: Handling Errors

· 8 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The Excel VBA Err object allows you to capture and manage runtime errors in your macros, preventing them from stopping your script and allowing you to display user-friendly messages or execute alternative code. To do this, you must use the On Error GoTo statement to direct program flow to a specific error-handling routine, and then use the Err object's properties (like Number, Description, and Source) to identify and respond to the error.

What You'll Need

  • A computer running Microsoft Excel (2010 or later is recommended for the best experience).
  • A basic understanding of VBA programming concepts, such as variables, subroutines, and the macro editor.
  • A spreadsheet with data to test your error-handling code.

Step-by-Step

  1. Open the Visual Basic for Applications Editor. In Excel, press the shortcut keys Alt + F11 on your keyboard. This will open the VBA editor window. If you are on a Mac, you can usually find this under the Tools menu and selecting Macro > Visual Basic Editor.
  2. Insert a new Module. In the VBA editor, you should see a project explorer on the left side. Right-click on the project name for your workbook (usually listed under VBAProject (YourWorkbookName.xlsm)) and select Insert > Module. This creates a blank module where you can write your code.
  3. Create a Subroutine. In the code window of the new module, type the word Sub followed by a name for your routine. For example, Sub TestErrorHandling(). Press Enter and type End Sub on a new line. This is the container for your code.
  4. Write the code that will generate an error. To demonstrate error handling, you need code that can fail. A common way to do this is to try to access a cell that does not exist or divide a number by zero. Add the following lines of code to your subroutine, between the Sub and End Sub statements:
Dim myValue As Integer

' This line intentionally causes an error by dividing by zero
myValue = 10 / 0

' This line will never be reached if the error occurs
MsgBox "This message will not be shown."
  1. Implement the error-handling routine. You will structure your code to have a section that handles errors. At the very top of your subroutine, after the variable declarations, add the following line to redirect program flow to a label named ErrorHandler if an error occurs:
On Error GoTo ErrorHandler
  1. Add the ErrorHandler label and logic. Below your normal code (but before the End Sub line), add the label and the code that will run when an error is caught. The label must be at the start of a line and end with a colon (:).
ErrorHandler:

' Display a message box with the error number and description
MsgBox "Error number: " & Err.Number & vbCrLf & "Description: " & Err.Description, vbExclamation, "An Error Occurred!"

' You can also use the Resume statement to continue execution
' Resume Next will continue with the line after the error
Resume Next

' Or Resume to go back to the line that caused the error
' Resume
  1. Run the macro. Return to your Excel spreadsheet. Press Alt + F8 to open the Macro dialog box. Select your TestErrorHandling macro and click Run.
  2. Observe the result. When you run the macro, the script will execute normally until it hits the division by zero. The On Error GoTo ErrorHandler line will cause the program to jump to the ErrorHandler label. The error-handling code will display a message box showing the error number (11) and a description (Divide by Zero). After you dismiss the message box, the Resume Next statement will cause the program to continue with the next line of code after the error.

Common Mistakes

1. Not resetting the Err object

After handling an error, the Err object's properties (like Number and Description) remain set to the error you just handled. If you don't reset them explicitly, they will persist for the rest of the module. To prevent this, use the Err.Clear statement at the end of your error-handling routine. This is particularly important if you have multiple error-handling routines in the same module.

2. Using Resume without a label or Next

The Resume statement must be followed by a label (like Resume ErrorHandler) or the keyword Next. Using just Resume without specifying where to go will cause the script to loop infinitely, constantly jumping back to the line that caused the error. This can crash your application if not handled carefully.

3. Placing the label incorrectly

The error-handling label must be defined in the same procedure where the On Error GoTo statement is used. If you try to use a label from a different subroutine, the script will not find it and will raise a compilation error.

4. Using Exit Sub instead of Exit Function

If you are working within a function (Sub vs. Function), make sure to use Exit Function to exit the routine cleanly. Using Exit Sub in a function will cause a runtime error because it is not a valid command for that data type.

Tips

  • Use descriptive error messages. Instead of just showing Err.Description, which can be technical and confusing for end-users, create your own custom message. You can use the error number as a key to look up a more user-friendly description in a Select Case statement.
  • Log errors for debugging. In a real-world application, it is helpful to log errors to a text file or a specific worksheet. This allows you to troubleshoot issues that might not be reproducible for the end-user.
  • Use On Error Resume Next for specific, isolated operations. You can use On Error Resume Next for a single line of code. If that line fails, the script will continue without stopping. You can then check Err.Number to see if it is not zero, indicating an error occurred, and handle it accordingly.
  • Handle the critical 0 error. A common mistake is to treat Err.Number = 0 as meaning no error occurred. However, Err.Number = 0 can also be returned by successful code. Always check for a non-zero number to determine if an error has occurred. It is safer to check If Err.Number <> 0 Then rather than If Err.Number = 0 Then.

Troubleshooting

My error-handling code is not being reached.

This is the most common issue when learning error handling. The On Error GoTo statement only works for errors that occur after it is executed. If you place the On Error GoTo ErrorHandler statement at the very end of your subroutine, it will never have a chance to catch any errors. You must place it immediately after your variable declarations and before any code that could potentially fail.

I am getting a 'Sub or Function not defined' error.

This error usually means that the label you are trying to jump to with the Resume statement does not exist in the current scope. Double-check that you have spelled the label name correctly and that it appears in the same procedure as the On Error GoTo statement.

The macro stops but no message box appears.

If the script stops but the MsgBox does not appear, it is likely that the error is happening in the MsgBox statement itself. A classic example is trying to show a message box with a variable that has not been set or has a type mismatch. If the error occurs inside the error-handling routine, the error-handling routine will not run because it is the same routine that is already in an error state. To debug this, try commenting out the MsgBox line and adding a simple Debug.Print statement to the Immediate Window to see if the code reaches that point.

My code loops infinitely.

An infinite loop with error handling is almost always caused by using the Resume statement without a label or the keyword Next. The script will keep jumping back to the line that caused the error, which will cause the same error again, and the loop will continue until you force-quit the Excel application.

Frequently Asked Questions

What is the difference between On Error GoTo 0 and On Error Resume Next?

On Error GoTo 0 turns off any error handling that is currently active in the current procedure. It does not resume normal execution after an error; it simply means that if an error occurs, the script will stop and display the default error dialog box. On Error Resume Next tells the script to ignore the error and continue with the next line of code. This is useful when you want to perform a specific operation that might fail, and you want to check for the error afterwards.

Can I have multiple error-handling routines in one macro?

Yes, you can have multiple error-handling routines. You can use different labels for each one and use the On Error GoTo statement to direct the program to a different routine depending on where the error occurred. This allows you to handle different types of errors in different ways.

Does the Err object persist after a macro finishes?

Yes, the Err object retains its values until the Err.Clear statement is executed or a new error occurs. It is generally good practice to clear the Err object at the end of your error-handling routine to ensure that it does not interfere with the rest of your code.

How do I handle errors in a UserForm?

Error handling in a UserForm works the same way as in a standard subroutine. You can use the On Error GoTo statement within the UserForm's code module. However, you must be careful when displaying error messages to users, as the error dialog box might be hidden behind the UserForm itself.