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

Jim DeMarco

"Pro Excel 2007 VBA"


Listing 7-10. GetXMLData Subroutine with Modifications
Sub GetXMLData()
Dim sFileName As String
sFileName = "C:\Book\Chapters\Chapter 3\files\cd.xml"
If FileExists(sFileName) Then
ActiveWorkbook.XmlImport URL:= _
sFileName, ImportMap:= _
Nothing, Overwrite:=True, Destination:=Range("$A$1")
Else
MsgBox "Could not find the requested file", vbOKOnly, "File Not Found"
End If
End Sub
CHAPTER 7 n DEBUGGING AND ERROR HANDLING 277
Let??™s take a look at what we changed:
??? We took the string containing the file name out of the XmlImport method call and
assigned it to the variable sFileName.
??? We then wrapped our XmlImport method call in an If statement. Based upon the existence
of the file, we either import the data or present the user with the friendly message
shown in Figure 7-39.
Figure 7-39. Friendly error message: File Not Found
The moral of this story in this case is that the best defense is a good offense. By considering
in advance where our code might fail, we can avoid errors and provide users with feedback
they can use.
Trapping Specific Errors
A rule of thumb when considering error handling is that error handling should not be an afterthought
or something to add later. Trap your errors when you create your code.
nTip Three good error handling rules to live by are (1) check for the error, (2) handle it, and (3) proceed
accordingly.
Returning our attention to the DebugExample01.xlsm file, let??™s trap for the type mismatch
error we got in our first go around with this file.


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