In addition to regular variables, Visual Basic often uses variables that represent a reference to an object. It turns out that using variables for object references not only reduces and simplifies the program text but also significantly speeds up its execution.
The use of an object variable differs slightly from that of ordinary variables: it is necessary not only to declare such a variable but also, before using it, to assign it a corresponding object with the special operator Set. The syntax for declaration and assignment is as follows:
Dim <VariableName> As Object Set <VariableName> = <ObjectReference>
Sometimes, when declaring such a variable, it is convenient to specify in advance a particular type of object—you can use any specific object from the Microsoft Office object model, for example:
Dim MyBase As Database Set MyBase = CurrentDb()
TIP
If you need to improve the performance of your program, it is recommended to use specific objects of the Microsoft Office model when describing object variables, rather than the universal description Object.
An object variable will point to an object until we assign it, with another Set operator, either a reference to another object of the same type or the value Nothing, which means that the variable does not contain any reference, for example:
Set txt = Nothing
After such an operation, the variable continues to exist, although it does not refer to any object. With another Set operator, it can again be assigned a reference to an object.
NOTE
Keep in mind that object variables, unlike ordinary variables containing values, contain only references to objects, not the objects themselves or their copies.