CVErr Function |
No
CVErr(errornumber)
errornumber
Use: Required
Data Type: Long
Any valid number.
A Variant of subtype Error containing an application-defined error number.
Creates user-defined errors in user-created procedures. For example, you can use CVErr to pass back error codes from a function, which allows you to handle exceptions in the data rather than going to the full extent of raising an error and invoking full error-handling routines. While the difference may appear subtle, in practice the CVErr function offers a much more gentle approach to handling exceptions that aren't threatening to the stability of the application.
The code CVErr(8001) returns "Error 8001."
Public Function GetValue(strText As String) As Variant If IsNumeric(strText) Then GetValue = strText If GetValue <= 0 Then GetValue = CVErr(10001) End If Else GetValue = CVErr(10001) End If End Function Private Sub Command1_Click() Dim varNumber As Variant Dim lngNumber As Long varNumber = GetValue(Text1.Text) If TypeName(varNumber) = "Error" Then lngNumber = 0 MsgBox "Please enter a positive integer in the text box." Else lngNumber = varNumber End If End Sub
Although the return value from CVErr may appear to be a string, it is in fact a Variant of subtype Error. Take care, therefore, not to directly assign the return value of CVErr to a string variable, or to any other strongly typed variable. For example, the following seemingly straightforward code generates a runtime "Type Mismatch" error:
Function MyFunc(iValue as Integer) As String If iValue > 0 Then MyFunc = "Correct" Else MyFunc = CVErr(80001) End If End Function
The way you should handle this is to explicitly convert the return value to a string data type using the CStr function. Alternately, you can assign the return value to a variant and determine whether its data subtype is Error when the function returns.
CVErr isn't the same as Err.Raise. Err.Raise invokes error handlers and assigns values to the Err object, whereas CVErr doesn't.
Typically, you use inline code to handle an error raised by CVErr.