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 ...

Get VB & VBA in a Nutshell: The Language now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.