Set (statement)

Syntax 1

Set object_var = object_expression

Syntax 2

Set object_var = New object_type

Syntax 3

Set object_var = Nothing


Assigns a value to an object variable.


Syntax 1

The first syntax assigns the result of an expression to an object variable. This statement does not duplicate the object being assigned but rather copies a reference of an existing object to an object variable.

The object_expression is any expression that evaluates to an object of the same type as the object_var.

With data objects, Set performs additional processing. When the Set is performed, the object is notified that a reference to it is being made and destroyed. For example, the following statement deletes a reference to object A, then adds a new reference to B.

 Set a = b

In this way, an object that is no longer being referenced can be destroyed.


Syntax 2

In the second syntax, the object variable is being assigned to a new instance of an existing object type. This syntax is valid only for data objects.

When an object created using the New keyword goes out of scope (that is, the Sub or Function in which the variable is declared ends), the object is destroyed.


Syntax 3

The reserved keyword Nothing is used to make an object variable reference no object. At a later time, the object variable can be compared to Nothing to test whether the object variable has been instantiated:

  Set a = Nothing
  If a Is Nothing Then Beep


This example creates two objects and sets their values.

Sub Main()
  Dim document As Object
  Dim page As Object
  Set document = GetObject("c:\resume.doc")
  Set page = Document.ActivePage
End Sub

See Also

= (statement); Let (statement); CreateObject (function); GetObject (function); Nothing (constant).

More information