All errors can be identified by a unique error id. You can use this id to tell which error occurred, and to give a suitable error message. The simplest way to catch and error is the On Error Resume Next statement. When an error occurs, the error number is stored in the Variable Err, and code execution continues as if nothing has happened. If you know an error is likely to occur on a certain line, you can write some code which can catch this error.
The following code attempts to delete the file C:\test.txt. If it does not exist it displays a message saying so.
Sub Command1_Click
On Error Resume Next ' Enable error trapping
Kill "C:\test.txt"
If Err = 53 Then ' The File Not Found error occurred
Msgbox "C:\test.txt was not found"
End If
End Sub
The error code for File Not Found is 53, and as that was the last error to occur, it was stored in the variable Err.
Comments