Global error handling

I’ve searched solution for global error handling in internet  – but I think there is no this kind of solution. Therefore I’ve made simply code with global error handling.

When I write application code I’m always trying add main procedure with roots to other procedures. There is global variable ErrorStatus to checking if error happened in other procedures.

If you don’t use global ErrorStatus variable and add unique codes lines for whole module when error happened VBA will return code line of main procedure. Do you prefer other solution?

Global error handling example:

' This is simply solution with global error handling in module / project
' Please notice code lines are added for whole module not procedure
' When error happened error line is shwoing, module and procedure name

Public ErrorMessage, ErrorStatus, ErlLine, ModName, ProcName

Public Sub MainMacro()

Dim i, a, s As Long

1   On Error GoTo ErrorMessage
2   ModName = "Module1"
3   ProcName = "MainMacro"
4   i = 1
5   a = 2

6   Macro1 'Calling other procedure
7   If ErrorStatus = True Then
8       GoTo ErrorMessage
9   End If

10  Macro2 'Calling other procedure
11  If ErrorStatus = True Then
12      GoTo ErrorMessage
13  End If

14  s = 3
15  Exit Sub

ErrorMessage:

16  If Erl <> 0 Then
17      Debug.Print "Code Line: " & Erl & Chr(10) & "Module: " & ModName & Chr(10) & "Procedure: " & ProcName
18  Else
19      Debug.Print "Code Line: " & ErlLine & Chr(10) & "Module: " & ModName & Chr(10) & "Procedure: " & ProcName
20  End If

End Sub

Private Sub Macro1()
' In this sub everything is ok

Dim i, a, x As Long

21  On Error GoTo ErrorMessage
22  ProcName = "Macro1"
23  i = 2
24  a = 2
25  x = i * a
26 Exit Sub

ErrorMessage:

27  ErrorStatus = True
28  ErlLine = Erl

End Sub

Private Sub Macro2()
' In this sub is error

Dim i, x As Long
Dim a As String

29  On Error GoTo ErrorMessage
30  ProcName = "Macro2"
31  i = 2
32  a = "dd"
33  x = i * a 'error with multiplication long and string variables
34  Exit Sub

ErrorMessage:

35  ErrorStatus = True
36  ErlLine = Erl

End Sub

1 thought on “Global error handling

Leave a Reply

Your email address will not be published. Required fields are marked *