Handling Errors in VB/VBA/VBS/ASP

Using the Err Object

To force an error to appear, in order to find the context, description and related help files for the topic at hand, you can use the following function. Call the public function, after placing it in a module, by the following code;

'// Form Code
'Create a form and ad a command button named Command1

Private Sub Command1_Click()
    Call GetErrData(TheNumberHere)
End Sub


'// Module Code

Public Function GetErrData(ByRef ErrorNumber As Long)
On Error GoTo ErrHandler

Err.Raise (ErrorNumber) ' this brief call to the event handler Raises the error

' Note that the Err.Source would be of little help here since
' this would be the calling project that you are in.

Exit Function
ErrHandler:
MsgBox "This is the error info..." & vbCrLf & _
"Number: " & Err.Number & vbCrLf & _
"Description " & Err.Description & vbCrLf & _
"Help Context ID" & Err.HelpContext & vbCrLf & _
"Help File" & Err.HelpFile, vbCritical, "ERROR MESSAGE"
Err.Clear   ' destroy the error and…
Resume Next
End Function


The following function will print out all available errors to a text file called, AllErrors.txt in the same location as your application file is stored.

'// Form Code
'Create a form and ad a command button named Command1

Private Sub Command1_Click()
    Call GetAllErrors()
    MsgBox "The Error document has been created", vbExclamation, "Finished!"
End Sub


'// Module Code

Public Function GetAllErrors()
'clean out residual error tags
Err.Clear
On Error GoTo ErrHandler
Dim I As Long, F As Integer, ErrFile As String
Dim MessageTxt As String

ErrFile = App.Path & "\AllErrors.txt"

F = FreeFile
Open ErrFile For Output As #F
Print #F, "Err.Number|Err.Description|Err.HelpContext|Err.HelpFile"

    For I = 1 To 65535 'all possible valid Long err numbers 'Loop the numbers and call them one by one Err.Raise (I)
GoHere:
' On resuming after getting the error message, go here
   
'only print the messages clearly defined
If MessageTxt <> "" And _
InStr(1, Trim(MessageTxt), "Application-defined or", vbTextCompare) = 0 Then
    Print #F, MessageTxt
End If

    Next I
Close #F

Exit Function
ErrHandler:
MessageTxt = Err.Number & "|" & _
 Err.Description & "|" & _
 Err.HelpContext & "|" & _
 Err.HelpFile
Err.Clear
Resume GoHere   ' Resume execution at the GoHere line label
End Function



For further details on the error object, please refer to the following topics in the Visual Basic help: Err Object, Trappable Errors, Error Function

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” - Martin Fowler