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 253 | Next

Jim DeMarco

"Pro Excel 2007 VBA"


7. Type the following line label:
Err_Handle:
8. Press Enter.
When we enabled error handling by adding the On Error GoTo statement, we referred it to
this label. You can name yours according to your own naming convention. Just be sure the
label used at the top of the procedure is the same as that used to name the error handler section
of code at the bottom of the procedure.
9. Add the following code at the insertion point:
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
If an error occurs, the code redirects to the Err_Handle section. Here we placed conditional
logic that looks for a specific error number. If we were aware of other error conditions,
we could simply add them to the If...Else block or even use a Select Case statement.
Inside the If statement, we are assigning the appropriate error message to the sErrMsg
variable based on what error occurred. Then we show the user the message. The last line of the
error handler section tells the code where to resume once the error is dealt with. In this case,
we??™re telling it to resume at the line label Exit_Function where we assign an output value to
our function.
CHAPTER 7 n DEBUGGING AND ERROR HANDLING 280
10. Save the code.
11. In Excel, run the AddSalesTotal Macro.
Our friendly message is displayed to the user informing her of the issue with the data, as
shown in Figure 7-41.


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