Name

Terminate Event

Syntax

Private Sub Class_Terminate( )

Description

The Terminate event is fired when an instance of a class is removable from memory.

Rules at a Glance

  • The Terminate event applies to classes defined with the Class...End Class construct.

  • Instances of a class are removed from memory by explicitly setting the object variable to Nothing or by the object variable going out of scope.

  • If a script ends because of a runtime error, a class’s Terminate event isn’t fired.

Example

The following example shows a typical Terminate event in a class object that decrements a global instance counter used to ensure that only a single instance of a particular utility object is created. When the counter reaches 0, the global object reference to the utility object is destroyed.

Private Sub Class_Terminate(  )

    glbUtilCount = glbUtilCount - 1
    If glbUtilCount = 0 then
        Set goUtils = Nothing
    End If
    
End Sub

Programming Tips and Gotchas

  • Because the Terminate event is fired when an object becomes removable from memory, it is possible, but not recommended, for the Terminate event handler to add references back to itself and thereby prevent its removal. However, in this case, when the object actually is released, the Terminate event handler will not be called again.

  • The Terminate event is fired under the following conditions:

    • An object goes out of scope.

    • The last reference to an object is set equal to Nothing.

    • An object variable is assigned a new object reference.

  • The Terminate event is fired when an object is ...

Get VBScript in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.