CVErr Function

Description

Returns a Variant of subtype Error containing an error number specified by the user.

Syntax

CVErr(errornumber)

The errornumber argument is any valid error number.

Remarks

Use the CVErr function to create user-defined errors in user-created procedures. For example, if you create a function that accepts several arguments and normally returns a string, you can have your function evaluate the input arguments to ensure they are within acceptable range. If they are not, it is likely that your function will not return what you expect. In this event, CVErr allows you to return an error number that tells you what action to take.

Note that implicit conversion of an Error is not allowed. For example, you can't directly assign the return value of CVErr to a non-Variant variable. However, you can perform an explicit conversion (using CInt, CDbl, and so on) of the value returned by CVErr and assign that to a variable of the appropriate data type.

See Also

Data Type Summary, IsError Function.

Example

This example uses the CVErr function to return an Error Variant. The user-defined function CalculateDouble returns an error if the argument passed to it isn't a number. CVErr is useful for returning user-defined errors from user-defined procedures. Use the IsError function to test if the value is an error.


' Define CalculateDouble Function procedure.
Function CalculateDouble(Number)
    If IsNumeric(Number) Then
        CalculateDouble = Number * 2    ' Return result.
    Else
        CalculateDouble = CVErr(2001)    ' Return a user-defined error 
    End If    ' number.
End Function

This example inserts the seven cell error values into cells A1:A7 on Sheet1.


myArray = Array(xlErrDiv0, xlErrNA, xlErrName, xlErrNull, _
    xlErrNum, xlErrRef, xlErrValue)
For i = 1 To 7
    Worksheets("Sheet1").Cells(i, 1).Value = CVErr(myArray(i - 1))
Next i

This example displays a message if the active cell on Sheet1 contains a cell error value. You can use this example as a framework for a cell-error-value error handler.


Worksheets("Sheet1").Activate
If IsError(ActiveCell.Value) Then
    errval = ActiveCell.Value
    Select Case errval
        Case CVErr(xlErrDiv0)
            MsgBox "#DIV/0! error"
        Case CVErr(xlErrNA)
            MsgBox "#N/A error"
        Case CVErr(xlErrName)
            MsgBox "#NAME? error"
        Case CVErr(xlErrNull)
            MsgBox "#NULL! error"
        Case CVErr(xlErrNum)
            MsgBox "#NUM! error"
        Case CVErr(xlErrRef)
            MsgBox "#REF! error"
        Case CVErr(xlErrValue)
            MsgBox "#VALUE! error"
        Case Else
            MsgBox "This should never happen!!"
    End Select
End If