Terminate Event |
Syntax
Private Sub object_Terminate( ) Private Sub Class_Terminate( )
object
Use: Required
Data Type: Object
A Form, MDIForm, User control, Property Page, or a VBA UserForm.
Description
The Terminate event is fired when the last instance of an object or class is removed from memory.
Rules at a Glance
Instances of an object or class are removed from memory by explicitly setting the object variable to Nothing or by the object variable going out of scope.
The Terminate event of a form-based object is fired after the Unload event.
If an application 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 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
If an application is terminated using the End statement prior to removing all instances of a class or form from memory, the Terminate event of that class isn't fired. This is the main reason you shouldn't use the End statement to terminate an application. Instead, you should use a Sub Main procedure. Specify Sub Main as the start-up procedure of your application; when program execution reaches the End Sub statement ...
Get VB & VBA in a Nutshell: The Language 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.