Error handling is a critical skill for any Excel VBA developer. When users interact with your macros, they might enter invalid data, reference non-existent ranges, or trigger other unexpected conditions. Professional applications anticipate these scenarios and handle them gracefully.
There are three main types of errors in VBA:
This lesson focuses on handling runtime errors, which are the most common in user-facing applications.
The foundation of VBA error handling is the On Error
statement, which comes in three forms:
Directs code to a specific label when an error occurs
Ignores the error and continues with next line
Disables current error handling
Private Sub CommandButton1_Click() On Error GoTo err_handler num1 = InputBox("Enter first number") num2 = InputBox("Enter second number") MsgBox num1 / num2 Exit Sub err_handler: MsgBox "Error: " & Err.Description & vbCrLf & _ "Please enter valid numbers and ensure denominator isn't zero", _ vbExclamation, "Calculation Error" End Sub
Key improvements:
Err.Description
to show specific error detailsvbCrLf
for better message formattingPrivate Sub CommandButton2_Click() Dim firstNum As Double, secondNum As Double On Error GoTo input_error firstNum = InputBox("Enter first number") secondNum = InputBox("Enter second number") On Error GoTo calculation_error MsgBox "Result: " & firstNum / secondNum, vbInformation, "Division Result" Exit Sub calculation_error: Select Case Err.Number Case 11 'Division by zero MsgBox "Error: Cannot divide by zero!", vbCritical, "Math Error" Case 6 'Overflow MsgBox "Error: Number is too large!", vbCritical, "Math Error" Case Else MsgBox "Unexpected error " & Err.Number & ": " & Err.Description, _ vbCritical, "Error" End Select Exit Sub input_error: If IsNumeric(firstNum) Then MsgBox "Invalid second number entered", vbExclamation, "Input Error" Else MsgBox "Invalid first number entered", vbExclamation, "Input Error" End If Resume Next End Sub
Enhancements include:
Select Case
for multiple error conditionsAs Double
Private Sub LogError(errNumber As Long, errDescription As String, _ Optional procedureName As String = "") Dim logSheet As Worksheet On Error Resume Next 'Prevent errors in error handler! Set logSheet = ThisWorkbook.Sheets("ErrorLog") If logSheet Is Nothing Then Set logSheet = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) logSheet.Name = "ErrorLog" logSheet.Range("A1:D1").Value = Array("Timestamp", "Procedure", "Error #", "Description") End If With logSheet.Cells(logSheet.Rows.Count, 1).End(xlUp).Offset(1, 0) .Value = Now .Offset(0, 1).Value = procedureName .Offset(0, 2).Value = errNumber .Offset(0, 3).Value = errDescription End With End Sub
VBA provides the built-in Err
object with several useful properties:
Property | Description |
---|---|
Number | Numeric code identifying the error |
Description | Text description of the error |
Source | Name of the object/application that generated the error |
HelpFile | Path to help file related to the error |
HelpContext | Context ID for help topic |
Here are some frequently encountered error numbers:
Error # | Description |
---|---|
6 | Overflow (number too large) |
7 | Out of memory |
9 | Subscript out of range |
11 | Division by zero |
13 | Type mismatch |
1004 | Application-defined or object-defined error |
Copyright ® 2020 Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page