Syntax for defining the current error handling method in VBA

On any line of my code, can I use Debug.Print () along with some other command to find out what happens if my code encounters an error on that line?

Can I use some expression in Debug.Print to find out if the current error handling procedure is needed for Goto 0, Resume Next or Go to some label?

I imagine something like:

Debug.Print(OnErrorMode) 

I'm looking for a way to determine if a particular line of code will be a GoTo 0 error (stop and show the error), Resume Next (skip the line) or GoTo Label (go to the label), given that On Error may be buried somewhere in my code, which I cannot find. Is it possible?

+5
source share
1 answer

For more than ten years of using VBA and VB (5 and 6), I have never had a single link that even remotely suggests that it is possible to determine what error capture conditions exist. Although the compiler knows for sure, it is not displayed.

It seems to me that your problem may be related to how you structure the error capture.

I end the routines in a single On Error Goto statement located in the same routine as On Error. I have a way out, and when an error occurs, I log what happened to fix the error. Then I can use debug.print or create a line with debugging information that is added 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 template that I use is areas in which there is a possibility that an error may occur, for example, opening a file (files may be missing) or a database. then I use error capture, for example, as a catch catch block.

 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 it easier to handle errors, and debugging is as simple as compiling a single On error statement. Note that err.number lists the error code return, so you can add logic to handle the various types of errors.

+6
source

Source: https://habr.com/ru/post/1212212/


All Articles