The On Error always clears the Err variable ( Erl will also reset to 0). Theoretically, this means that you can fix this problem by moving the On Error statement below the ToString = ... (or by deleting the error handler in the ToError function in ToError ), but unfortunately this will not always work.
Each component (DLL, ActiveX EXE, etc.) referenced by your project essentially gets its own instance of Err in memory. So, if your MainApp.exe causes an error that is passed to ToError (for example, in a separate ErrorHandling.dll ), the DLL will not see the Err variable that your EXE sees. Each of them has its own private variables Err .
At least two ways to solve the problem that I can think of:
Method 1
As Zian Choy mentions , you can add additional parameters to your ToError function, one for each property of the Err object that you need access to.
the code
Public Function ToError( _ ByVal strErrSource As String, _ ByVal nErrNumber As Long, _ ByVal sErrDescription As String, _ ByVal nLineNumber As Long) As String
Using example
Then you would have to call it this way from the error handlers, passing it all the corresponding values ββfrom the current Err object along with Erl :
ToError Err.Source, Err.Number, Err.Description, Erl
If you also want App.Title , you will also have to add an additional parameter to ToError , since App.Title will be equal to the App.Title project, where ToError , and not the component where the error was raised. This is important if ToError is in another project.
Method 2
You can make your ToError calls a little less verbose by passing the Err object itself as a parameter to the function, however the first thing your ToError function should do in this case is immediately to keep a copy of all the properties you need, since the next On Error statement will clear the variable.
the code
Public Function ToError(ByVal oError As ErrObject, ByVal nLineNumber As Long) As String 'Copy the important Err properties first, ' 'before doing anything else... ' Dim strErrSource As String Dim nErrNumber As Long Dim strErrDescription As String strErrSource = oError.Source nErrNumber = oError.Number strErrDescription = oError.Description On Error Goto errHandle 'More code here '...
Usage example
ToError Err, Erl