Microsoft Office Tutorials and References
In Depth Information
You can declare an object using a Dim , a Public , or a Private statement using two different
forms. Here’s the first form:
Dim ObjectVariable As ClassName
This statement simply reserves space for ObjectVariable and the variable now has a type of
Dim ObjectVariable As New ClassName
This second form does everything the previous form did, but will automatically create a new
object the first time ObjectVariable is referenced.
Objects and Nothing
Visual Basic for Applications includes a special value called Nothing . You can use this value
only with objects. Nothing is the value associated with an object variable that doesn’t cur
rently point to an instance of a class. An object variable declared with a Dim statement will
initially be set to Nothing .
You can determine if a new instance of a class has been created by using Is Nothing in an If
statement like this:
If ObjectVariable Is Nothing Then
Warning Although the expression ObjectVariable Is Not Nothing might make perfect
sense in English, Visual Basic for Applications doesn’t understand it. If you need to verify
that an object variable refers to an instance of an object, you should use the expression
Not ObjectVariable Is Nothing .
The Is Nothing test results in a Boolean value and can be used anywhere you can use a Boolean
You can use the following statement to destroy an object:
Set ObjectVariable = Nothing
This statement will release the reference to the object and set the object variable to its unini
tialized state. Assuming that there was only one object variable that pointed to the object, this
statement will also destroy the object and release all the resources associated with it.
However, if multiple object variables point to this object, all of them must be set to Nothing
before the object is destroyed. For example, in the following code fragment, the object created
from MyClass continues to exist, even though ObjectVariable1 was set to Nothing .