Set Statement

Named Arguments

No

Syntax

Set objectvar = {[New] objectexpression | Nothing}


objectvar

Use: Required

Data Type: Object

The name of the object variable or property.


New

Use: Optional

Type: Keyword

Creates a new instance of the object.


objectexpression

Use: Required

Data Type: Object

An expression evaluating to an object.


Nothing

Use: Optional

Type: Keyword

Assigns the special data type Nothing to objectvar, thereby releasing the reference to the object.

Description

Assigns an object reference to a variable or property.

When using Dim, Private, Public, ReDim, or Static to declare an object variable, the variable is assigned a value of Nothing unless the New keyword is used in the statement. The Set statement is then required to assign a reference to an instance of the object referred to in the declarative statement.

Rules at a Glance

  • Before the Set statement is used, objectvar must have been declared either as a generic object data type or (preferably) using the same object type as objectexpression. For example:

    Dim objVar As Object
    Dim objExcel As Excel.Application
    
    Set objVar = Word.Application
    Set objExcel = Excel.Application

  • objectvar doesn't hold a copy of the underlying object; it simply holds a reference to the object.

  • If the New keyword is used, a new instance of the class is immediately created. This fires that class's Initialize event.

  • The New keyword can't be used with intrinsic data types or dependent objects; in other words, objects and classes must be createable.

  • If objectvar holds a reference to an object when the Set statement is executed, the current reference is released and the new one referred to in objectexpression is assigned.

  • objectexpression can be any of the following:

    • The name of an object.

    • A variable that has been previously declared and instantiated using the Set statement and that refers to the same type of object.

    • A call to a function, method, or property that returns the same type of object.

  • By assigning Nothing to objectvar, the reference held by objectvar to the object is released.

Example

The following example uses the Set statement to create instances of two ActiveX objects.

Private Function GetEmployeeName(sEmpNo As String) As String
Dim oEmps As Employees
Dim oEmp As Employee

Set oEmps = New Employees

If oEmps.Exists(sEmpNo) Then
   Set oEmp = oEmps.Employee(sEmpNo)
   GetEmployeeName = oEmp.Name
   Set oEmp = Nothing
End If
Set oEmps = Nothing

End Function

Programming Tips and Gotchas

  • You can have more than one object variable referring to the same object. However, bear in mind that a change to the underlying object using one object variable is reflected in all the other object variables that reference that object. For example, consider the following code fragment, in which the objColorCopy object reference is set equal to the objColor object:

    Dim objColor As CColor, objColorCopy As CColor
    Set objColor = New CColor
    Set objColorCopy = objColor
    
    objColor.CurrentColor = "Blue"
    Debug.Print objColorCopy.CurrentColor

    Since both objColor and objColorCopy reference a single object, the value of the CurrentColor property is Blue in both cases.

  • If you use the New keyword when declaring an object, you don't have to use the Set statement to instantiate the object. In most cases, this is more a matter of programming style than of programming optimization or performance issues. The following snippets show the two methods of instantiating an early bound object (that is, an object that has had a project-level reference created using the references dialog):


    Method 1

    Dim myObj As New SomeClass


    Method 2

    Dim myObj As SomeClass
    Set myObj = New SomeClass

    There are, however, certain instances where you can only use the New keyword with the Set statement, as the next example shows. Here a recordset has been created from a database, and each record is assigned to an object that is held in a collection. With each loop, a new instance of the class has to be created. Therefore, the New keyword is used with the Set statement:

    Dim oVar As clsNames
    Do While Not rsNames.EOF
       Set oVar = New clsNames
       oVar.FirstName = rsNames!FName
       oVar.LastName = rsNames!LName
       mcolNames.Add oVar
       Set oVar = Nothing
    Loop

  • It's often essential (and certainly good programming practice) to set object references to Nothing once the application is finished using them. For example, you must set an object to Nothing when you have created one or a number of sub (or dependent) objects from within another object. If you don't release the references to the child objects from the client code when you have finished with them, you can't explicitly release the reference to the main object from the client. This snippet shows how it should be done:

    Dim myMainObj as MainClass
    Dim mySubObj as SomeSubClass
        
    Set myMainObj = New MainClass
       Set mySubObj = MainClass.Item(1)
          'work with the sub object
       Set MySubObj = Nothing
    Set MyMainObj = Nothing

    Each object instance maintains a counter of the number of current references to it. If the object referenced by the object variable has no other references when object variable is set to Nothing (that is, its counter is decremented to zero), the object's Terminate event is fired, and the object unloads from memory.

    During the development stage, you should use conditional compilation and the Debug.Print method to check that all references to an object or class are being released correctly. This can be done as shown in the snippet below within the class's Terminate event:

    #If ccDebug Then
        Debug.Print "Class myClass Terminated"
    #End If

    This is important because although you are prevented from specifying circular object references (where one class references another and—perhaps indirectly—the referenced class also holds a reference to the class referencing it) within the references dialog, you can build in circular object references quite easily without realizing it or even deliberately, as a result of your application design. Classes with circular references don't release from memory until the application terminates. For more details, see Chapter 4.

  • When trying to discover whether or not an object reference has been successfully assigned, you should determine if the object variable has been assigned Nothing. However, you can't use the equality comparison operator (=) for this purpose; you must use the Is operator, as the following code snippet shows:

    If objectvar Is Nothing Then
        ... 'assignment failed
    End If

  • While the Set statement used with the New keyword provides for early binding to an externally createable object, a type library may not be available for a particular automation object, or the precise automation object to be used may not be known at design time. In that case, externally createable objects can be instantiated at runtime (i.e., can be late bound) by using the Set statement along with the CreateObject function. For example:

    Dim oMainObject As MainLib.MainObject
    Set oMainObject = CreateObject("MainLib.MainObject")

    In addition, from VB6 onward, CreateObject supports an extra parameter specifying the remote machine on which the object is registered. For example:

    Dim oRemServ As MainLib.MainObj
    If ServerOnLine("NTSERV1") Then
       Set oMainObject = CreateObject("MainLib.MainObj", _
                                      "NTSERV1")
    Else
       Set oMainObject = CreateObject("MainLib.MainObj", _
                                      "NTSERV2")
    End If

See Also

Dim Statement; Friend Statement; Private Statement; Public Statement; Chapter 5
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.171.19