MS-Access / Getting Started

Error Trapping for File Access

Error trapping is almost always a must when dealing with file I/O. Why? Have you ever tried to access a CD-ROM from Windows Explorer, only to get an error message because there is no CD-ROM in the CD-ROM drive? What if the CD-ROM is in the drive, but the file is not found, or better yet-the file is there but it's corrupted?

There are all types of potential errors when dealing with data files and file I/O. Your best bet is to plan ahead and create error-trapping or error-handling routines. In fact, it is safe to promote error trapping in any procedure that opens, writes, reads, appends, or closes files. An adequate facility for capturing file I/O errors is to use VBA's Err object. The Err object contains preexisting codes for various known errors such as "File Not Found," "Disk Not Ready," and many more that can be used to your advantage.

Here's an error-handling routine for a quiz game that uses the Err object to check for specific errors when the game attempts to open a file in the form Load event:

Private Sub Form_Load()
    On Error GoTo ErrorHandler:

Like any other error-handling routine, I start my procedure by declaring an error-handling label with an On Error GoTo statement. You can insert unique labels throughout your code as done here with the BeginHere: label.

BeginHere:

Labels can serve useful purposes as long as you keep their existence minimal and easy to follow. As you see later in the code, I choose the BeginHere: label as a good starting point in this procedure.

Open "quiz.dat" For Input As #1
    Exit Sub

After opening the sequential data file, the procedure is exited, providing no errors have occurred.

ErrorHandler:
    Dim liResponse As Integer

If an error does occur in opening the file, my guess is that it is one of the following error conditions (error codes). You can see in the following code using the Select Case structure to check for specific Err object codes. If an error code is found, the user is prompted with an opportunity to fix the problem. If the user decides to retry the operation, the program resumes control to the BeginHere: label.

Select Case Err.Number

    Case 53

	'File not found
	liResponse = MsgBox("File not found!", _
	  vbRetryCancel, "Error!")

	If liResponse = 4 Then 'retry
	  Resume BeginHere:
	Else
	  cmdQuit_Click
	End If

    Case 71

	'Disk not ready
	liResponse = MsgBox("Disk not ready!", _
	  vbRetryCancel, "Error!")

	If liResponse = 4 Then 'retry
	  Resume BeginHere:
	Else
	  cmdQuit_Click
	End If

    Case 76

	liResponse = MsgBox("Path not found!", _
	  vbRetryCancel, "Error!")

	If liResponse = 4 Then 'retry
	  Resume BeginHere:
	Else
	  cmdQuit_Click
	End If

    Case Else

	MsgBox "Error in program!", , "Error"
	cmdQuit_Click

    End Select

End Sub
[Previous] [Contents]