Raising Custom Defined Errors

The descriptions for a great many error messages must have been written by programmers whose native language was something other than English. Some of them make for interesting reading, but there are quite a few that don't go too far toward educating you about the reason for the problem (or its resolution). Raising your own errors provides the flexibility of displaying more user-friendly or user-specific error messages.

The VBA Err object provides a Raise method, which lets you construct and fire your own custom errors. You must supply everything the Err object needs to return anything useful, which includes the error number, description, source, optional path to a help file, and the ContextID, which identifies a specific topic in the help file.

The syntax for the Err.Raise method is as follows:

Err.Raise number, source, description, helpfile, helpcontext

For example, the following procedure demonstrates the typical method for trapping errors and raising your own:

Const MyContextID = 1010407 1 Define a constant for ContextID

Private Sub ErrorTest() Dim xlApp As Object On Error Goto ErrorTest_Err

'If Excel is already open, get a handle to 'the existing instance.

Set xlApp = GetObject(, "Excel.Application")

' Other code

ErrorTest_Exit:

On Error Resume Next xlApp.Quit Set xlApp = Nothing Exit Sub

ErrorTest_Err:

Select Case Err.Number

Case 42 9 'ActiveX component can't create object 'Raise the error.

strErrDescr = "Unable to open Excel. It may not be installed." Err.Raise vbObjectError + 513, TypeName(Me), _ "Excel is not currently running", _ "c:\MyProj\MyHelp.Hlp", MyContextID Case Else

'Something else went wrong.

Err.Raise Err.Number, Err.Source, Err.Description End Select

You might have noticed the TypeName function. TypeName returns information about a variable; for example:

TypeName(strMyString) returns String TypeName(intMyInteger) returns Integer TypeName(db.TableDefs("Table1")) returnsTableDef But when passed a class object, it returns the object's Name property.

0 0

Post a comment