An object variable is a pointer to an address of the memory location that stores the object.
An object variable is a variable that represents an entire object.
A non-object variable is a pointer to the memory location directly.
Also make your code easier to read.
Since object variables are pointers it is possible for more than one object variable to refer to the same object.
If you are using object variables then it is important to keep track of what they are referencing. It is not a good idea to have more than one object variable pointing to the same object.
You can have more than one variable referring to the same object (set one object variable equal to another)

Assigning an Object Variable

The Set statement is used to assign an object reference to an object variable.
Object variables should also be declared and assigned a type as with normal variables.

Dim objWorkbook As Workbook 
Set objWorkbook = ThisWorkbook

If you don't know the type, you can use the generic Object as a type.

Dim objWorkbook As Object 
Set objWorkbook = ThisWorkbook
Call MsgBox(objWorkbook.Name)

It is more efficient to use the specific object type if you can.
It is more efficient to create an object variable if you are going to refer to an object more than once.

What you should try to refrain from doing is declaring an Object datatype using the "New" keyword.
Including the New keyword in the Dim statement creates what is called an auto-instancing variable.
This does not create the object when the variable declaration is processed but instead automatically when the variable is first encountered in code.
This also means that you are unable to test whether the variable Is Nothing.

Dim objSomething As New MyObject 


Dim objSomething As MyObject 
Set objSomething = New MyObject

When it comes to assigning a value to a variable the syntax is slightly different for objects and non objects.
You must use the Set keyword when assigning a value to an object variable.

Set objDocument = ActiveDocument 
Set objWorkbook = ActiveWorkbook
Set objPresentation = ActivePresentation

You must use the "SET" statement when you want an object variable to refer to an object.
You can assign object varaiables to the generic "Object" type although this type should only be used when the type of the object is unknown.
You must use the Set keyword when assigning a value to an object.

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