The VBA CVErr Function

Related Functions:
VBA Error
VBA IsError

Description

The VBA CVErr function returns an Error data type, relating to a user-specified error code.

The syntax of the function is:

CVErr( Expression )

Where the supplied Expression is the required error code.


VBA CVErr Function Example

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, the CVErr function is used to create an Error data type.

' Function to divide two numbers.
Function performDiv( num1 As Double, num2 As Double )
if num2 = 0 Then
' Return Error data type for error code 11 (represents division by zero).
performDiv = CVErr( 11 )
' performDiv is now equal to Error 11.
Else
' Perform the division.
performDiv = num1 / num2
End If
End Function

In the above function, if the second supplied number is zero, the function returns the error data type 'Error 11' (which represents a division by zero).

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