Share via


Creating a New Instance of a Class

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

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

In addition, you can 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 are less likely to introduce unexpected bugs when your code controls the creation of the instance. In addition, when you are building a custom object model, you often must perform certain operations at the time that an object is created, so it is critical to know where in your code that will happen. If you use the second method, Microsoft® Visual Basic® for Applications (VBA) creates the object in memory the first time that you refer to it, so you cannot check to see whether it is equal to Nothing; performing this check creates the object if it does not already exist.

See Also

Why Build Your Own Objects? | Basic Class Concepts | Creating Property Procedures | Creating Events and Event Procedures | Extending Objects Through Interfaces | Designing Object Models | Creating Custom Objects for Web Pages