Signal errors in VB6 using CVErr and IsError

It can be extremely useful to signal an error in VB6 with a function's return value. Learn how to use the CVErr and IsError functions to track down errors.

Functions in VB6 are often used to perform data manipulation on numbers or strings and return the result. Suppose there is the possibility of an error in the function—not a run-time error but a program-definer error such as invalid data. If you want to return a value from the function that signals an error to the calling code, you simply use the CVErr and IsError functions.

The CVErr function converts a type Variant into the subtype Error. You can detect this with the IsError function. Here's the strategy:

  1. Declare your function with a Variant return type, which will work for both string and number data.
  2. If the function executes properly, assign the return value as usual:
MyFunction = value
  1. If there's a problem and you need to return an error value, use CVErr to return an error with some numerical value:
MyFunction = CVErr(SomeNumericalValue)
  1. In the calling program, use IsError like this:
ReturnValue = MyFunction()
If IsError(ReturnValue) Then
    ' Deal with error here.
    ' Deal with non-error return value here.
End If

The ability to signal an error with a function's return value is very useful in some situations.



Editor's Picks