In a complex procedure, you will find there are lots of places where errors can occur, and quite often are the same errors. If this is the case putting code after each line is a waste of space and time. A much more efficient way is to use the statement:
On Error GoTo LineLabel
This statements tell visual basic, that if an error occurs after this statement, to continue code execution at the LineLabel specified. The following code attempts to delete A: est.txt (this assumes A: is a disk drive). If an error occurs, it will give the appropriate error message. It will then attempt to get the size of C:fred.txt . Again, if an error occurs it will give the appropriate message. However it all uses the same code to detect the error.
Sub Command1_Click()
' If an error occurs GoTo FileError
On Error GoTo FileError
' Attempt to delete A: est.txt
Kill "A: est.txt"
' Attempt to get the size of C: est.txt
gFileSize = FileLen("A: est.txt")
Msgbox "File Size is: " & gFileSize
' Exit the procedure as no error has occurred
Exit Sub
FileError:
Select Case Err
Case 53
' The file does not exist. Inform the user
Msgbox "The file does not exist"
gFileSize = "<Unknown>"
Case 5
' The disk is not ready. Prompt user for action
Ans = Msgbox ("Insert a disk into Drive
A", vbAbortRetryIgnore)
If Ans = vbRetry Then
' The user chose Retry. Resume
code execution
' at where the error occurred
Resume
ElseIf Ans=vbIgnore Then
' The user chose to ignore. Resume code
execution
' at the line after where the
error occurred
Resume Next
Else
' The user chose abort. Exit
this procedure
Exit Sub
End If
Case Else
' unexpected error
Msgbox "An error occurred. " &
Err & " : " & Error
End Select
End Sub
FileLen returns the size of the specified file in bytes. Normally Err 75 would occur if the drive was not ready, however when using FileLen Err 5 occurs
Comments