O'Reilly logo

VB & VBA in a Nutshell: The Language by Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

4.3. Class Module Events

Unlike normal code modules, class modules support two events that are automatically defined when you add a class module to your project. These two standard events, the Initialize and Terminate events, are analogous to the class constructor and destructor in an object-oriented programming language like C++; they are fired automatically when a class is instantiated and destroyed, respectively.

An event handler is the code attached to a particular event. When the event is fired, the event handler is executed automatically. Like all event handlers, writing code to handle the Initialize and Terminate events is optional, but it's at the heart of sound VB programming. So let's look at some of the uses you can put these event handlers to and some of the rules relating to these two events.

4.3.1. The Initialize Event

Let's begin by examining precisely when the Initialize event is fired, then look at some possible applications for the Initialize event handler.

4.3.1.1. When is the Initialize event fired?

The firing of the Initialize event depends on how the class object is instantiated. If you use the combined method of declaring a New instance of an object:

Dim oVar As New svrObject

the Initialize event is fired when the first reference is made to a member of the class, and not when the class is declared as New. For example:

Dim oVar As New svrObject ' Initialize event not called oVar.AnyProp = sAnyVal ' Initialize event fired _ immediately prior to the Property ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required