This example illustrates the basics of error handling. Add the code below, with two command buttons cmdCreate and cmdDelete. First, try clicking cmdCreate. This will generate a message box saying that the path could not be found (unless you have a dir called C:fred), instead of VB generating and error... If your program was compiled to an EXE without error handling, your program would have closed... instead your user gets an error message, and your program continues to work! Likewise, if you click the Delete button, an error message is displayed, because the file does not exist...
The On Error Goto FileErr statement tells VB that if an error occurs, it should skip to the FileErr: statement, allowing you to 'trap' the error and deal with it accordingly.
Private Sub cmdCreate_Click()
On Error GoTo FileErr
Dim filenum As Integer
filenum = FreeFile
Open "C:fred ext.txt" For Output As filenum
Close filenum
Exit Sub
FileErr:
Select Case Err
Case 76
MsgBox "Path not found", ,
"Error"
Case Else
MsgBox "Unexpected error. Err
" & Err & " : " & Error, vbOKOnly, "Error"
End Select
End Sub
Private Sub cmdDelete_Click()
On Error GoTo FileErr
Kill "C:fred ext.txt"
Exit Sub
FileErr:
Select Case Err
Case 53
MsgBox "File not found", ,
"Error"
Case Else
MsgBox "Unexpected error. Err
" & Err & " : " & Error, , , "Error"
End Select
End Sub
Comments