Objects

Object is the general term for an instance of a class. Visual Basic has an Object type that you can use to create variables that reference any generic object; however, you usually want to create variables of a specific class of object. Objects are a special kind of variable because you can control when they are created. Other types of variables in Visual Basic are initialized whenever they are declared, but that’s not true with objects .

The easiest way to create an object variable is to include the New keyword in the variable declaration. For example, the following line creates a new object variable from the PublicClass class definition:

    Dim obj As New PublicClass

Once created, you can use that object’s properties and methods to do whatever it is you want to do. New is an executable statement; if you use it at the module level, the actual creation of the object is delayed till the first time the object is referenced within a procedure—a confusing situation that is best to avoid. If you declare an object variable at the module level, omit New, then create the object within a procedure explicitly. For example, the following code creates a global object variable and creates the object the first time UseObject runs:

    ' Global object variable
    Public g_obj As PublicClass

    Sub UseObject( )
        ' Create global object variable
        If g_obj Is "Nothing" Then Set g_obj = New PublicClass
        ' Show that the object exists
        Debug.Print g_obj.CREATED
    End Sub

There are a few significant things to point ...

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.