Microsoft Office 2000/Visual Basic Programmer's Guide |
To work with a custom object from code, you first create a new instance of the class that defines the object. When you create a new instance of a class, the object defined by the class is created in memory.
You can create a new instance of a class from within any type of module. Create an object variable of type ClassName, and then use the New keyword to assign a new instance of that class to the object variable.
For example, the following code creates a new instance of a custom class named System and assigns it to an object variable of type System
:
' Declare an object variable of type System.
Dim sysLocal As System
' Create a new instance of the System class and assign it to the object variable.
Set sysLocal = New System
You can also declare the object variable and assign a new instance of the class all in one step, as shown in the following code fragment:
Dim sysLocal As New System
The first method of declaring an object variable is generally preferable because you have control over when the new instance of the class is created in memory and thus more control over when memory resources are consumed. You're less likely to introduce unexpected bugs when your code controls the creation of the instance. In addition, when you're building a custom object model, you often need to perform certain operations at the time that an object is created, so it's critical to know where in your code that will happen. If you use the second method, VBA creates the object in memory the first time that you refer to it, so you can't check to see whether it is equal to Nothing; performing this check creates the object if it doesn't already exist.