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

Jim DeMarco

"Pro Excel 2007 VBA"

In Excel, run the AddSalesTotal macro again.
4. Click OK when the error message is displayed. The correct total for the numeric values
will be displayed, as shown in Figure 7-45.
Figure 7-45. Result of using Resume Next to complete our loop
Our On Error GoTo statement refers to a specific line label to handle errors. If you know
that any errors you might encounter in a routine are not going to be fatal and can be skipped,
you can use the On Error Resume Next statement.
Listing 7-14 shows a modified version of the GetSalesTotal function that uses On Error
Resume Next.
Listing 7-14. GetSalesTotal Function Using On Error Resume Next
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 Resume Next
For Each cell In RangeToTotal
temp = temp + cell.Value
Next cell
currReturn = temp
CHAPTER 7 n DEBUGGING AND ERROR HANDLING 284
Exit_Function:
GetSalesTotal = currReturn
Exit Function
End Function
On Error Resume Next essentially turns error trapping off. If there??™s a chance that another
section of your code could throw an error, you can turn error trapping back on by adding an
On Error GoTo statement inside your code. Figure 7-46 shows the GetSalesTotal function
with error trapping turned off for the loop, but turned back on again for the return variable
assignments.
Figure 7-46. Error trapping turned on by adding an On Error GoTo statement
Now if an error should occur after the loop runs, we can trap it and handle it appropriately
in the error handler.


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