Creating an Instance of a Class

After typing all the necessary Property Get, Property Let, Sub, and function procedures for your VBA application in the class module, you are ready to create a new instance of a class, which is called an object. Before an object can be created, an object variable must be declared in a standard module to store the reference to the object. If the name of the class module is CEmployee, a new instance of this class can be created with the following statement:

Dim emp As New CEmployee

The emp variable will represent a reference to an object of the CEmployee class.

When you declare the object variable with the New keyword, VBA creates the object and allocates memory for it; however, the object isn't instanced until you refer to it in your procedure code by assigning a value to its property or running one of its methods.

You can also create an instance of the object by declaring an object variable with the data type defined to be the class of the object. For example:

Dim emp As CEmployee

Set emp = New CEmployee

If you don't use the New keyword with the Dim statement (as shown above), VBA does not allocate memory for your custom object until your procedure actually needs it.

0 0

Post a comment