Set Statement

Assigns an object reference to a variable or property or associates a procedure reference with an event.

Syntax

Set objectvar = {objectexpression | Nothing}

Arguments:

  • Objectvar: Required. Name of the variable or property; follows standard variable naming conventions.

  • Objectexpression: Optional Expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object of the same object type.

  • Nothing: Optional. Discontinues association of objectvar with any specific object or class. Assigning objectvar to Nothing releases all the system and memory resources associated with the previously referenced object when no other variable refers to it.

Note:

Either Objectexpression or Nothing, one of them is mandatory.

Remarks

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.

Example 1: Simple Assignment of the File System Object


Dim fso, file
Set fso = CreateObject("Scripting.FileSystemObject")  ' Create a FileSystemObject
Set tso = fso.CreateTextFile("C:\testfile.txt", True) ' Create a new text file
' Now you can work with the text stream object, such as writing to it
tso.WriteLine("Hello, VBScript!")
tso.Close  ' Always close the file when done