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:
- Declare
your function with a Variant return type, which will work for both string
and number data. - If
the function executes properly, assign the return value as usual:
MyFunction = value
- 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)
- In
the calling program, use IsError like this:
ReturnValue = MyFunction()
If IsError(ReturnValue) Then
' Deal with error here.
Else
' 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.
Advance your scripting skills to the next level with TechRepublic’s free Visual Basic newsletter, delivered each Friday. Automatically sign up today!