Creating an Instance of a Class

After typing all the necessary Property Get, Property Let, subprocedures, or function procedures for your VBA application in the class module, you are ready to create a new instance of a class, 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, then 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.

┬ęCustom Project 8-1 (Step 6): Creating an Instance of a Class

1. Activate the Visual Basic Editor window and choose Insert | Module to add a standard module to your application. Use the Properties window to change the name of the new module to EmpOperations.

2. Type the following declarations at the top of the EmpOperations module:

Option Compare Database Option Explicit Dim emp As New CEmployee Dim CEmployee As New Collection

Part I

The first declaration statement declares the variable emp as a new instance of the CEmployee class. The second statement declares a custom collection. The CEmployee collection will be used to store all employees' data.

0 0

Post a comment