The VBA CVErr function returns an Error data type, relating to a user-specified error code.
The syntax of the function is:
Where the supplied Expression is the required error code.
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
End Function
' Return Error data type for error code 11 (represents division by zero).
Else
performDiv = CVErr( 11 ) ' performDiv is now equal to Error 11.
' Perform the division.
End If
performDiv = num1 / num2 |
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.