The VBA Error Function

Related Function:


The VBA Error function returns the error message corresponding to a supplied error code.

The syntax of the function is:

Error( [ErrorNumber] )

Where [ErrorNumber] is an optional integer argument representing the required error number.

If the [ErrorNumber] argument is omitted, the Error function returns the most recent run-time error.

Note that:

VBA Error Function Examples

Example 1

The following VBA code uses the Error function to get the error messages for the error codes 5 and 11.

The last call to the Error function has no argument and so returns the most recent run-time error (none in this case).

' Display the error messages for different error codes.
Dim errMsg1 As String
Dim errMsg2 As String
Dim errMsg3 As String
errMsg1 = Error( 5 )
' Now, errMsg1 = "Invalid procedure call or argument".
errMsg2 = Error( 11 )
' Now, errMsg2 = "Division by zero".
errMsg3 = Error()
' Now, errMsg3 = "" (no run-time errors have yet occurred).

Example 2

The following example shows a simple VBA function that divides a supplied number by a second supplied number.

If the second supplied number is zero, a message box showing the corresponding error message is displayed.

' Function to divide two numbers.
Function performDiv( num1 As Double, num2 As Double )
if num2 = 0 Then
' Display the error message corresponding to error code 11 (represents division by zero).
MsgBox ( Error( 11 ) )
' Code to run if the divisor is zero.
performDiv = CVErr( 11 )
' Perform the division.
performDiv = num1 / num2
End If
End Function

In the above function, if the second supplied number is zero, the following message box is displayed:

Message Box Showing Error Message For Error Code 11

A useful list of VBA error codes and the corresponding error messages is provided on the Wiley Online Library website.