3.2 How do I connect a RecordSet to a table?
A RecordSet is useless unless it is associated with a table or a query in a database. Assuming that you want a RecordSet to
be associated with a table in the Access document’s own database, you can do the following:
Set myRecordSet = CurrentDb.OpenRecordSet("Contacts", dbOpenDynaset)
Several things need to be explains in this statement.
- Set
We have never used this keyword before, what does it do? This is one of those “unique” features of Visual
Basic. If Set is not specified, an assignment statement automatically selects the default property (if there is
one) of the variable (object) to the left of the equal symbol. However, the purpose of this statement is to initial
the object itself, rather than its default property. The reserved word Set makes sure that VB understands not
to use any default properties automatically.
- myRecordSet =
Nothing mysterious about this part. This is the variable (object) that we want to initialize.
- CurrentDB
CurrentDB refers to a “Database” object that corresponds to the database of the document that contains this
statement. In most cases, CurrentDB is the correct database to use. However, this also means that a RecordSet
in VBA can correspond to a table or a query that belongs to another database (Access 2007 document)!
- .OpenRecordSet
This is a method of a “Database” object. This particular method creates a RecordSet according to the
parameters.
- (Contacts
The first parameter is Contacts, which specifies the table or query in CurrentDB to associate with the
RecordSet. For a named table or query, this parameter only needs to refer to the name. However, you can also
specify an SQL SELECT statement to associate a RecordSet with a on-the-fly query that has no name.
- dbOpenDynaset)
The second parameter is dbOpenDynaset. This parameter specifies the behavior of the RecordSet.
dbOpenDynaset specifies that the RecordSet is a two-way portal to the associated table. VBA code can both
read and update rows in the table Contacts.