By using the CVErr() and IsError() functions and the Application.AccessError method, you can create your own functions that can return an error value if an error situation occurs in the function. Here's a short description of each function and method that can be used:
The CVErr() function converts a value to an Error data type, assigning it to a Variant variable.
The IsError() function checks to see whether a Variant is an Error data type.
The Application.AccessError method provides an error description without the error itself.
An example of using these commands is when you divide two numbers—either the function receives a text value instead of the number needed, or a zero is sent. Listing 7.10 shows the cmdTestCVErr_Click routine that calls the ap_ShowErrorCVErr subroutine, which passes back either the answer or an error number. Both cmdTestCVErr_Click and ap_ShowErrrCVErr are located on the TestErrors form.
Here are a few items to consider from Listing 7.10:
You'll want to type the return variable as a Variant and convert it to Integer to compare the number to error numbers.
Note the use of the IsError() function to test for an Error type value.
You'll want to declare the function as Variant as well because it can contain either the answer (in this case, a double) or an Error value.
Listing 7.11 shows the ap_ShowErrorCVErr() function, which passes back either an error number for various errors, or the answer itself if everything is okay.
Function ap_ShowErrorCVErr(varNumerator As Variant, varDenominator As _ Variant) As Variant '-- Check and make sure correct data type If Not IsNumeric(varNumerator) Or Not IsNumeric(varDenominator) Then ap_ShowErrorCVErr = CVErr(2001) '-- Make sure no zero for denominator ElseIf CDbl(varDenominator) = 0 Then ap_ShowErrorCVErr = CVErr(11) '-- If ok, perform action Else ap_ShowErrorCVErr = CDbl(varNumerator) / CDbl(varDenominator) End If End Function |
From Listing 7.11, you can see that
If the entered data isn't numeric, a custom error number is assigned to the return value.
If the denominator is 0, an error is sent back.
If all is OK, the answer is sent.
You can see from these examples that the CVErr() and IsError() functions give you that much more control over your application.
That's about it for all the commands used in error handling. Now it's time to look at some practical ways to use these commands.
3.147.238.70