IsError Function
Returns a Boolean value indicating whether an expression is an error value.
Syntax
IsError(expression)
Parameters
expression(Required): Variant expression to test
Return Value
Returns a Boolean:
- True if the expression is an error value created by CVErr
- False if the expression is not an error value
- Only detects error values created with CVErr function
- Does not detect runtime errors or error objects
- Works with Variant variables containing error values
- Returns False for Null, Empty, or any non-error value
Remarks
The IsError function is used to determine whether a Variant expression contains an error value:
- Only detects
CVErrerror values (VariantsubtypevbError) - Does not detect
Errobject or runtime errors - Error values are created using
CVErrfunction - Useful for propagating errors through
Variantreturns - Common in functions that need to return error indicators
- Error values are different from Null or Empty
- Can be used to check function return values for errors
- Error values preserve error numbers through call chains
- Use
CVErrto create error values,IsErrorto detect them VarType(expr) = vbErrorprovides same functionality- Error values are uncommon in modern VB6 code
- Most code uses
Err.Raisefor error handling instead
Typical Uses
- Error Propagation: Check if function returned an error value
- Error Value Detection: Identify
CVErrvalues inVariantdata - Function Return Checking: Validate function results
- Array Processing: Detect errors in array elements
- Data Validation: Distinguish errors from valid data
- Legacy Code: Work with older code using
CVErrpattern - Error Chains: Propagate errors through multiple function calls
- Conditional Logic: Branch based on error presence
Basic Usage Examples
' Example 1: Create and detect error values
Dim result As Variant
result = CVErr(5) ' Create error value with error number 5
If IsError(result) Then
Debug.Print "Result is an error" ' This prints
Debug.Print "Error number: " & CLng(result) ' Prints: 5
End If
' Example 2: Distinguish error from other values
Dim testVar As Variant
testVar = CVErr(13)
Debug.Print IsError(testVar) ' True - error value
testVar = 13
Debug.Print IsError(testVar) ' False - regular number
testVar = Null
Debug.Print IsError(testVar) ' False - Null is not error
testVar = Empty
Debug.Print IsError(testVar) ' False - Empty is not error
' Example 3: Function returning error or value
Function SafeDivide(numerator As Double, denominator As Double) As Variant
If denominator = 0 Then
SafeDivide = CVErr(11) ' Division by zero error
Else
SafeDivide = numerator / denominator
End If
End Function
' Usage
Dim result As Variant
result = SafeDivide(10, 2)
If IsError(result) Then
MsgBox "Error in calculation: " & CLng(result)
Else
MsgBox "Result: " & result ' Prints: 5
End If
' Example 4: Process array with error checking
Function ProcessValues(values() As Variant) As Variant
Dim i As Integer
Dim total As Double
total = 0
For i = LBound(values) To UBound(values)
If IsError(values(i)) Then
ProcessValues = CVErr(CLng(values(i))) ' Propagate error
Exit Function
End If
total = total + values(i)
Next i
ProcessValues = total
End Function
Common Patterns
' Pattern 1: Safe function call with error checking
Function SafeGetValue(source As Variant, key As String) As Variant
On Error Resume Next
SafeGetValue = source(key)
If Err.Number <> 0 Then
SafeGetValue = CVErr(Err.Number)
End If
On Error GoTo 0
End Function
' Usage
Dim value As Variant
value = SafeGetValue(myDict, "key")
If IsError(value) Then
MsgBox "Error: " & CLng(value)
End If
' Pattern 2: Coalesce - return first non-error value
Function CoalesceValues(ParamArray values() As Variant) As Variant
Dim i As Long
For i = LBound(values) To UBound(values)
If Not IsError(values(i)) And Not IsNull(values(i)) And Not IsEmpty(values(i)) Then
CoalesceValues = values(i)
Exit Function
End If
Next i
CoalesceValues = CVErr(xlErrNA) ' All values were invalid
End Function
' Pattern 3: Get error number from error value
Function GetErrorNumber(errorValue As Variant) As Long
If IsError(errorValue) Then
GetErrorNumber = CLng(errorValue)
Else
GetErrorNumber = 0 ' No error
End If
End Function
' Pattern 4: Chain operations with error propagation
Function CalculateResult(a As Variant, b As Variant) As Variant
If IsError(a) Then
CalculateResult = a ' Propagate first error
Exit Function
End If
If IsError(b) Then
CalculateResult = b ' Propagate second error
Exit Function
End If
' Perform calculation
CalculateResult = a + b
End Function
' Pattern 5: Validate all values before processing
Function AllValid(ParamArray values() As Variant) As Boolean
Dim i As Long
For i = LBound(values) To UBound(values)
If IsError(values(i)) Or IsNull(values(i)) Then
AllValid = False
Exit Function
End If
Next i
AllValid = True
End Function
' Pattern 6: Convert error to message
Function ErrorToMessage(value As Variant) As String
If IsError(value) Then
Select Case CLng(value)
Case 5
ErrorToMessage = "Invalid procedure call"
Case 7
ErrorToMessage = "Out of memory"
Case 9
ErrorToMessage = "Subscript out of range"
Case 11
ErrorToMessage = "Division by zero"
Case 13
ErrorToMessage = "Type mismatch"
Case Else
ErrorToMessage = "Error " & CLng(value)
End Select
Else
ErrorToMessage = "No error"
End If
End Function
' Pattern 7: Default value for errors
Function ValueOrDefault(value As Variant, defaultValue As Variant) As Variant
If IsError(value) Or IsNull(value) Or IsEmpty(value) Then
ValueOrDefault = defaultValue
Else
ValueOrDefault = value
End If
End Function
' Pattern 8: Find first error in array
Function FindFirstError(arr As Variant) As Variant
Dim i As Long
If Not IsArray(arr) Then
FindFirstError = CVErr(13) ' Type mismatch
Exit Function
End If
For i = LBound(arr) To UBound(arr)
If IsError(arr(i)) Then
FindFirstError = arr(i)
Exit Function
End If
Next i
FindFirstError = Null ' No errors found
End Function
' Pattern 9: Count errors in array
Function CountErrors(arr As Variant) As Long
Dim i As Long
Dim count As Long
If Not IsArray(arr) Then
CountErrors = 0
Exit Function
End If
count = 0
For i = LBound(arr) To UBound(arr)
If IsError(arr(i)) Then
count = count + 1
End If
Next i
CountErrors = count
End Function
' Pattern 10: Safe numeric conversion
Function SafeCDbl(value As Variant) As Variant
On Error Resume Next
Dim result As Double
result = CDbl(value)
If Err.Number <> 0 Then
SafeCDbl = CVErr(Err.Number)
Else
SafeCDbl = result
End If
On Error GoTo 0
End Function
Advanced Usage Examples
' Example 1: Error-aware calculator class
Public Class SafeCalculator
Public Function Add(a As Variant, b As Variant) As Variant
If IsError(a) Then
Add = a
Exit Function
End If
If IsError(b) Then
Add = b
Exit Function
End If
On Error Resume Next
Add = a + b
If Err.Number <> 0 Then
Add = CVErr(Err.Number)
End If
On Error GoTo 0
End Function
Public Function Divide(numerator As Variant, denominator As Variant) As Variant
If IsError(numerator) Then
Divide = numerator
Exit Function
End If
If IsError(denominator) Then
Divide = denominator
Exit Function
End If
If denominator = 0 Then
Divide = CVErr(11) ' Division by zero
Exit Function
End If
Divide = numerator / denominator
End Function
Public Function GetErrorMessage(errorValue As Variant) As String
If Not IsError(errorValue) Then
GetErrorMessage = "No error"
Exit Function
End If
GetErrorMessage = "Error " & CLng(errorValue) & ": " & _
Error$(CLng(errorValue))
End Function
End Class
' Example 2: Variant array processor with error handling
Public Class VariantArrayProcessor
Public Function Map(arr As Variant, callback As String) As Variant
' Apply callback function to each element, propagate errors
Dim result() As Variant
Dim i As Long
If Not IsArray(arr) Then
Map = CVErr(13) ' Type mismatch
Exit Function
End If
ReDim result(LBound(arr) To UBound(arr))
For i = LBound(arr) To UBound(arr)
If IsError(arr(i)) Then
result(i) = arr(i) ' Preserve error
Else
On Error Resume Next
result(i) = Application.Run(callback, arr(i))
If Err.Number <> 0 Then
result(i) = CVErr(Err.Number)
End If
On Error GoTo 0
End If
Next i
Map = result
End Function
Public Function Filter(arr As Variant) As Variant
' Remove error values from array
Dim result() As Variant
Dim i As Long, count As Long
If Not IsArray(arr) Then
Filter = Array()
Exit Function
End If
ReDim result(LBound(arr) To UBound(arr))
count = LBound(arr) - 1
For i = LBound(arr) To UBound(arr)
If Not IsError(arr(i)) Then
count = count + 1
result(count) = arr(i)
End If
Next i
If count >= LBound(result) Then
ReDim Preserve result(LBound(result) To count)
Filter = result
Else
Filter = Array()
End If
End Function
End Class
' Example 3: Data validator with detailed error reporting
Public Class DataValidator
Private m_errors As Collection
Private Sub Class_Initialize()
Set m_errors = New Collection
End Sub
Public Function ValidateRecord(record As Variant) As Boolean
Dim i As Long
Dim fieldName As String
m_errors.Clear
If Not IsArray(record) Then
ValidateRecord = False
Exit Function
End If
For i = LBound(record) To UBound(record)
If IsError(record(i)) Then
m_errors.Add "Field " & i & ": Error " & CLng(record(i))
ElseIf IsNull(record(i)) Then
m_errors.Add "Field " & i & ": Null value"
ElseIf IsEmpty(record(i)) Then
m_errors.Add "Field " & i & ": Empty value"
End If
Next i
ValidateRecord = (m_errors.Count = 0)
End Function
Public Function GetErrors() As Collection
Set GetErrors = m_errors
End Function
Public Function GetErrorSummary() As String
Dim msg As String
Dim i As Long
If m_errors.Count = 0 Then
GetErrorSummary = "No errors"
Exit Function
End If
msg = "Found " & m_errors.Count & " error(s):" & vbCrLf
For i = 1 To m_errors.Count
msg = msg & "- " & m_errors(i) & vbCrLf
Next i
GetErrorSummary = msg
End Function
End Class
' Example 4: Function composition with error handling
Function Compose(value As Variant, ParamArray functions() As Variant) As Variant
' Apply functions in sequence, stop on first error
Dim i As Long
Dim result As Variant
result = value
For i = LBound(functions) To UBound(functions)
If IsError(result) Then
Compose = result ' Propagate error
Exit Function
End If
On Error Resume Next
result = Application.Run(functions(i), result)
If Err.Number <> 0 Then
Compose = CVErr(Err.Number)
Exit Function
End If
On Error GoTo 0
Next i
Compose = result
End Function
' Usage:
' result = Compose(10, "DoubleValue", "AddTen", "FormatResult")
' If IsError(result) Then MsgBox "Error in processing"
Error Handling
The IsError function itself does not raise errors:
' IsError is safe to call on any value
Debug.Print IsError(123) ' False
Debug.Print IsError("text") ' False
Debug.Print IsError(CVErr(5)) ' True
Debug.Print IsError(Null) ' False
Debug.Print IsError(Empty) ' False
' Common pattern: check and extract error number
If IsError(value) Then
Dim errNum As Long
errNum = CLng(value) ' Extract error number
MsgBox Error$(errNum) ' Get error description
End If
Performance Considerations
- Fast Operation:
IsErroris a very fast type check - Overhead:
CVErr/IsErrorpattern has more overhead thanErr.Raise - Modern Alternative: Most code uses structured error handling instead
- Legacy Code: Primarily seen in older VB6 and Excel VBA code
Best Practices
- Prefer
Err.Raise: Use structured error handling for most scenarios - Check Returns: Always check
IsErrorfor functions returningVariant - Propagate Errors: Pass error values through call chains when appropriate
- Document Behavior: Clearly document when functions return error values
- Extract Numbers: Use
CLng(errorValue)to get error number from error value - Combine Checks: Check
IsError,IsNull, andIsEmptyfor complete validation - Error Messages: Convert error numbers to messages for user display
- Avoid Overuse:
CVErrpattern less common in modern VB6 code
Comparison with Related Functions
| Function | Purpose | Returns | Use Case |
|---|---|---|---|
IsError |
Check if CVErr value |
Boolean |
Detect error values |
CVErr |
Create error value | Variant (Error) |
Return error indicator |
IsNull |
Check if Null | Boolean |
Detect Null values |
IsEmpty |
Check if uninitialized | Boolean |
Detect Empty Variants |
VarType |
Get variant type | Integer |
Detailed type information |
Err.Raise |
Raise runtime error | N/A | Structured error handling |
Error$ |
Get error description | String |
Error message from number |
CVErr vs Err.Raise
' CVErr pattern (older style)
Function OldStyleDivide(a As Double, b As Double) As Variant
If b = 0 Then
OldStyleDivide = CVErr(11) ' Return error value
Else
OldStyleDivide = a / b
End If
End Function
If IsError(result) Then
MsgBox "Error: " & CLng(result)
End If
' Err.Raise pattern (modern style)
Function ModernDivide(a As Double, b As Double) As Double
If b = 0 Then
Err.Raise 11, , "Division by zero" ' Raise error
Else
ModernDivide = a / b
End If
End Function
On Error Resume Next
result = ModernDivide(10, 0)
If Err.Number <> 0 Then
MsgBox "Error: " & Err.Description
End If
Platform and Version Notes
- Available in all VB6 versions
- Part of VBA core functions
- Returns
Booleantype - Only detects
CVErrerror values (Variant subtype vbError) - Does not detect
Errobject or runtime errors - More common in Excel VBA than desktop VB6
- Excel has predefined errors:
xlErrDiv0,xlErrNA,xlErrName,xlErrNull,xlErrNum,xlErrRef,xlErrValue
Limitations
- Only detects
CVErrerror values, not runtime errors - Does not provide error description (use
Error$function) - Cannot distinguish different error types beyond number
- Less flexible than structured error handling (Try/Catch equivalent)
- Error values can be confusing when mixed with normal values
- Not widely used in modern VB6 applications
- Requires
Variantreturn types (cannot use with typed returns)
Related Functions
CVErr: Create error value from error numberError$: Get error description from error numberIsNull: Check ifVariantisNullIsEmpty: Check ifVariantisEmptyVarType: Get detailedVarianttype informationErr.Raise: Raise runtime error (preferred modern approach)