SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 254 | Next

Jim DeMarco

"Pro Excel 2007 VBA"


Figure 7-41. User-friendly error message
12. Click OK to continue.
As shown in Figure 7-42, there is a small issue with the output from the GetSalesTotal
function. It returned a value of 0.
Figure 7-42. Zero value returned from GetSalesTotal function
Let??™s see what happened. Return to the VBE and look at the GetSalesTotal function
(Listing 7-13).
CHAPTER 7 n DEBUGGING AND ERROR HANDLING 281
Listing 7-13. GetSalesTotal Function with Error Handling
Function GetSalesTotal(RangeToTotal As Range) As Currency
Dim currReturn As Currency
Dim cell As Range
Dim temp As Currency
Dim sErrMsg As String
On Error GoTo Err_Handle
For Each cell In RangeToTotal
temp = temp + cell.Value
Next cell
currReturn = temp
Exit_Function:
GetSalesTotal = currReturn
Exit Function
Err_Handle:
If Err.Number = 13 Then
sErrMsg = "A value in your data may not be numeric. Please check your data"
Else
sErrMsg = "An unexpected error " & Err.Number & " has occurred"
End If
MsgBox sErrMsg, vbOKOnly, "Error"
Resume Exit_Function
End Function
Debugging the Error Handler
After our error message is displayed, we tell our code to resume at the Exit_Function line
label. Since we know the code worked fine with all numeric values in our original example and
our error message was displayed successfully upon trapping the error, lets add a breakpoint at
the point where we resume execution, as shown in Figure 7-43.
Figure 7-43. Breakpoint added in error handler
CHAPTER 7 n DEBUGGING AND ERROR HANDLING 282
1.


Pages:
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266