Handling Errors with Inline Code

In previous sections of this chapter, you've used the On Error GoTo statement to jump to an error-handling subroutine and then resume running the rest of your code. You can also handle errors without branching to a subroutine.

If you anticipate that a particular statement might cause an error, include an On Error Resume Next statement before the potential error-causing statement to prevent the application from being interrupted. You can then test the value of the Err function and proceed accordingly.

The following procedure is a revision of the FileExists procedure shown earlier in this chapter. This revised version doesn't branch to a subroutine; instead, it handles errors in-line.


Function FileExists(filename)
Dim Msg

Const ERR_DISKNOTREADY = 71, ERR_DEVICEUNAVAILABLE = 68

' Resets the Err code to zero; handles errors inline
On Error Resume Next

CheckOnFile:
    FileExists = (Dir(filename) <> "")
    If Err = ERR_DISKNOTREADY Then
        Msg = "Put a floppy disk in the drive and close the drive door."
        If MsgBox (Msg, vbExclamation + vbOKCancel) = vbOK Then
            GoTo CheckOnFile
        End If
        FileExists = False
    ElseIf Err = ERR_DEVICEUNAVAILABLE Then
        Msg = "This drive or path doesn't exist: " & filename
        MsgBox Msg, vbExclamation
        FileExists = False
    ' If not successful, and if not one of the above errors, handle
    ElseIf Err <> 0 Then
        Msg = "Unexpected error #" & Str(Err) & ": " & Error(Err)
        MsgBox Msg, vbCritical
        FileExists = False
    End If


End Function