Share via


Visual Basic Concepts

Handling Run-Time Errors in ActiveX Components

Error-handling code is especially important when you're working with ActiveX components, because code from the component is used from within your Visual Basic application. Where possible, you should include code to handle errors that the component may generate. For example, it is good practice to check for the error that occurs if a user unexpectedly closes a component application:

Function StartWord()
' Starts Microsoft Word.
On Error Goto ErrorTrap

   ' Declare a Microsoft Word Application variable
   ' and an integer variable for error trap.
   Dim wdApp As Word.Application
   Dim iTries As Integer

   ' Assign an object reference.
   Set wdApp = New Word.Application

   ' Release object variable.
   Set wdApp = Nothing

   Exit Function

ErrorTrap:
   ' Trap for the error that occurs if Microsoft Word
   ' can't be started.
   Select Case Err.Number
      Case 440               ' Automation error.
         iTries = iTries + 1
         ' Make up to 5 attempts to restart Word.
         If iTries < 5 Then
            Set wdApp = New Word.Application
            Resume
         Else
            Err.Raise Number:=VBObjectError + 28765, _
            Description:= "Couldn't restart Word"
         End If
      Case Else
         Err.Raise Number:= Err.Number
   End Select
End Function

If any error other than error 440 occurs in the preceding example, the procedure displays the error and raises an error. The application that provides the object might pass back its own error. In some cases, an application might use the same error code that Visual Basic uses for a different error. In these cases, you should use On Error Resume Next and check for errors immediately after each line that might cause an error. This type of error checking is called inline error-handling.

Testing for Object References

Before using an object variable in your code, you may want to make sure the variable holds a valid object reference. You can determine whether or not an object reference has been assigned to the variable by using Is Nothing. For example, the following code checks whether or not an object reference has been assigned to the variable wdDoc:

If wdDoc Is Nothing Then MsgBox "No object reference."

However, Is Nothing won't detect whether or not a valid object reference has become unavailable. For example, if you assign a Microsoft Word object reference to an object variable and Microsoft Word becomes unavailable, the variable will still hold a valid object reference. In this situation, use your error handler to trap the error that results when your code tries to use the variable.

For More Information   For information about the errors that a particular application might pass back, see that application's documentation. For more information about trapping errors, see "Debugging Your Code and Handling Errors."