The preceding sections have shown how to return a reference to an object in order to work with that object in Visual Basic. It’s possible to use an object reference throughout your code each time you need to refer to a particular object. However, your code runs more quickly if you declare an object variable to represent the object instead. An object variable is a variable that represents an object in Visual Basic. Object variables differ from regular variables in that they have no intrinsic value. They point to an object, not a value. In other words, an object variable points to an object’s representation in memory. All object variables that are assigned to an object point to the same object.
There are several advantages to using object variables. By using object variables to refer to objects in your code, you can:
Object variables are a special type of variable supported by Visual Basic. Each object type in DAO has a corresponding object variable type. For example, the Workspace object has a corresponding workspace object variable, the Database object has a corresponding database object variable, and so on.
To use an object variable, first declare the variable with the Dim statement and then use the Set statement to assign an object to it. The syntax is:
Dim ObjectVariable As ObjectType
Set ObjectVariable=SomeDataAccessObject
For example, the following code, which prints the names of all the fields in a table, uses object variables to refer to Database, TableDef, and Field objects. In this example, strDbPath
is the path to the database and strTableName
is the name of the table:
Dim dbs As Database Dim tdf As TableDef Dim fld As Field Set dbs = OpenDatabase(strDbPath) Set tdf = dbs.TableDefs(strTableName) For Each fld In tdf.Fields Debug.Print fld.Name Next fld