6

On any given line in my code, can I use Debug.Print() together with some other command to find out what would happen if my code would encounter an error on that line?

Can I use any statement within Debug.Print to find out if the current error handling procedure is to Goto 0, Resume Next or Goto some label?

I'm envisioning something like:

Debug.Print(OnErrorMode)

I am looking for a way to determine whether a specific line of code that errors will GoTo 0 (stop and show error), Resume Next (skip the line), or GoTo Label (jump to Label) given that an On Error might be buried somewhere in my code that I cannot find. Is that possible?

Chrismas007
  • 6,085
  • 4
  • 24
  • 47
user1283776
  • 19,640
  • 49
  • 136
  • 276

1 Answers1

7

In over a decade of using VBA, and VB (5 and 6), I have never seen a single reference that even remotely suggests that one may be able to determine what error trapping conditions exists. While the compiler surely knows, it is not exposed.

It seems to me that your problem may be in regards to how you are structuring your error trapping.

I wrap subroutines in a single On Error Goto statement, located in the same subroutine as the On Error. I have an exit and when the error occurs, I log what happened so I can fix the bug. I then can use debug.print or create a string with debugging information that is appended to the log.

Sub main()
         On Error GoTo Main_Error
         'Insert Code Here
         Exit Sub
         Main_Error:
         WriteLog Err.Number, Err.Description
        MsgBox ("The program encoutnered an error.")
    End Sub
    Private Sub WriteLog(ErrNum As Integer, ErrDes As String)
        Open "Errors.txt" For Append As #1
        Print #1, Now & "  " & ErrNum & " - " & ErrDes
        Close #1 
    End Sub

The second pattern I use is in areas in which there is a good chance that an error may occur, like opening a file (files might be missing), or a database. then I use the error trapping like a try catch block like so.

Private Function LoadFile() As Boolean
    On Error GoTo Main_Error
    'Code before a potentially error-prone statement
    On Error Resume Next
    Open "aMissingFile.txt" For Input As #1
    If Err.Number <> 0 Then
        MsgBox ("aMissingFile.txt is missing")
        LoadFile = False
        Exit Function
    End If
    On Error GoTo LoadFile_Error
    'The rest of your code
    LoadFile = True
    Exit Function
LoadFile_Error:
    WriteLog Err.Number, Err.Description
    MsgBox ("The program encoutnered an error.")
    LoadFile = False
End Function

This makes dealing with errors easier and debugging is as easy as commenting out a single On error statement. Note that err.number lists the error code return, so you can add logic to handle different types of errors.

Amen Jlili
  • 1,884
  • 4
  • 28
  • 51
Andrew Neely
  • 908
  • 11
  • 19