Checking for Error Values

Each error value you create must be associated with a specific error. After you've done this you can use the IsError function to test whether a particular error has occurred. You can test for specific user-defined error values the same way you test for specific built-in errors, using the Select Case statement or the If...Then...Else statement.

The following example uses the CVErr function to return an error value. The AreaOfCircle procedure asks for a radius value. The CheckData function checks the Radius variable and, if it isn't an acceptable number, converts it into one of two possible error values. In the AreaOfCircle procedure, the IsError function returns True if its argument is an error value.


Public NoRadius, NotANumber

Sub AreaOfCircle()
    Const PI = 3.14
    NoRadius = CVErr(50000)
    NotANumber = CVErr(50001)
    Radius = CheckData(InputBox("Enter the radius"))
    If IsError(Radius) Then
        Select Case Radius
            Case NoRadius
                MsgBox "Error: No radius given."
            Case NotANumber
                MsgBox "Error: Radius isn't a number."
            Case Else
                MsgBox "Unknown error."
        End Select
    Else        ' there's no error
        MsgBox "The area of the circle is " & (PI * Radius ^ 2)
    End If
End Sub
Function CheckData(TheRadius)
    If Not IsNumeric(TheRadius) Then
        CheckData = NotANumber
    ElseIf TheRadius = 0 Then
        CheckData = NoRadius
    Else
        CheckData = TheRadius
    End If
End Function

It's important to remember that if Visual Basic attempts to compare an error value with a number or other value in an expression, a run-time error will occur.


If NoRadius = 50000 Then...    'Causes an error. Cannot compare error to a                             'number or other value.

The following code doesn't cause an error because you can compare an error value with another error value.


If NoRadius = CVErr(50000) Then...

For more information about IsError or CVErr, see the appropriate topic in Help.