This keyword/value can only be used with variables declared as Object or Variant
An object variable that has not been initialised has a value of Nothing.
You must use the Is Operator to test for equality.
You cannot use an equal sign (=) when working with object variables, only simple data types.
An object data type can never equal 0 or "" (zero length string).

Initialising an Object

Dim oMyObject As Object 
If (oMyObject Is Nothing) Then
   Call MsgBox("nothing value")
End If

Assigning Nothing

Use the Set statement to assign the value Nothing to an object variable
You can use this to destroy a reference to an object.

Set myObject = Nothing 

To free an object variable so that it no longer points to anything, assign the "Nothing" keyword. (eg Set rgeRange = Nothing).
It is good programming practice to free object variables when they are no longer needed, since this can save resources.
An object variable is automatically set to "Nothing" when all its references are destroyed.

The Nothing keyword has several uses:
1) to release an object variable
2) to be returned from a function that has failed
3) to initialise an object variable

Set to Nothing

VBA handles reference counting automatically
When the last reference to an object is released the object is automatically removed from memory
When a reference variable goes out of scope it is automatically set to Nothing
There is no point including Set variable = Nothing just before the variable goes out of scope.

Not Nothing

These are all equivalent but the first one is the preferred syntax.

If (Not (oMyobject Is Nothing) = True) Then 
If Not (oMyobject Is Nothing) Then
If Not oMyobject Is Nothing Then

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext