Set Statement
Updated: April 2009
Assigns an object reference to a variable or property, or associates a procedure reference with an event.
Set objectvar = {objectexpression | New classname | Nothing}
' or
Set object.eventname = GetRef(procname)
To be valid, objectvar must be an object type consistent with the object being assigned to it.
The Dim, Private, Public, or ReDim statements only declare a variable that refers to an object. No actual object is referred to until you use the Set statement to assign a specific object.
Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable. Instead, a reference to the object is created. More than one object variable can refer to the same object. Because these variables are references to (rather than copies of) the object, any change in the object is reflected in all variables that refer to it.
Using the New keyword allows you to concurrently create an instance of a class and assign it to an object reference variable. The variable to which the instance of the class is being assigned must already have been declared with the Dim (or equivalent) statement.
Refer to the documentation for the GetRef function for information on using Set to associate a procedure with an event.
The following example includes a class declaration. The Set statement is used to create an instance of the class, and to reference an existing instance.
Class Customer
Private m_CustomerName
' CustomerName property.
Public Property Get CustomerName
CustomerName = m_CustomerName
End Property
Public Property Let CustomerName(custname)
m_CustomerName = custname
End Property
End Class
Dim custA, custB
' Create an instance of the Customer class,
' and assign it to the custA variable.
Set custA = New Customer
' Set a property of the custA object.
custA.CustomerName = "Fabrikam, Inc."
' Have the custB variable reference the
' same object as the custA variable.
Set custB = custA
' Because the custA and custB variables
' reference the same object, the property's
' value is the same in both.
MsgBox (custA.CustomerName)
MsgBox (custB.CustomerName)