An On Error
statement will always clear the Err
variable (Erl
will also be reset to 0). In theory this means you could fix the problem by moving the On Error
statement below the ToString = ...
line (or removing the error handler in the ToError
function altogether), but unfortunately that won't necessarily always work either.
Each component (DLL, ActiveX EXE, etc.) referenced by your project essentially gets its own Err
instance in memory. So, if your MainApp.exe
raises an error which gets passed to ToError
(residing in a separate ErrorHandling.dll
for example), the DLL won't see the Err
variable that your EXE sees. They each have their own private Err
variables.
There are a at least two ways around the problem that I can think of:
Method 1
As Zian Choy mentions, you could add additional parameters to your ToError
function, one for each property of the Err
object that you need access to.
Code
Public Function ToError( _
ByVal strErrSource As String, _
ByVal nErrNumber As Long, _
ByVal sErrDescription As String, _
ByVal nLineNumber As Long) As String
Example usage
You would then have to call like this from your error handlers like so, passing it all the relevant values from the current Err
object, along with Erl
:
ToError Err.Source, Err.Number, Err.Description, Erl
If you also want App.Title
, you're going to have to add an additional parameter to ToError
for that as well, since App.Title
will be equal to the App.Title
of the project where the ToError
method is defined, not the component where the error was raised. This is important if ToError
is in a different 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 store a copy of all the relevant properties you need since a subsequent On Error
statement will clear the variable.
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
'...
Example Usage
ToError Err, Erl