Microsoft Access 2010 Bible

(Rick Simeone) #1

Chapter 13: Accessing Data with VBA Code


493


Public Sub ExecuteCommand1
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandText = “tblCustomers”
Set rst = cmd.Execute
Debug.Print rst.GetString
rst.Close
Set rst = Nothing
End Sub

Notice the following actions in this procedure:

l A Recordset and a Command object are both declared and instantiated.

l (^) The Command object’s ActiveConnection property is set to the current project’s
Connection property.
l (^) The Command object’s CommandText property is set to the name of a table in the database.
l The recordset is populated by setting it to the value returned when the Command object is
executed.
Notice the recordset’s GetString method. GetString is a handy way to output everything
that’s in the recordset. Figure 13.11 shows the output from ExecuteCommand1 in the Debug
window.
Cross-Reference
The Debug window is thoroughly discussed in Chapter 14.
FIGURE 13.11
GetString is a convenient way to see what’s in a recordset.
This little example illustrates almost everything you need to know about ADO Command objects. A
Command object must be attached to an available Connection through its ActiveConnection
property. The ActiveConnection can be a connection string or an open Connection object.
It doesn’t make any difference where the Connection is pointing — an Access or SQL Server
database, Oracle or any other data source. The Command object uses the Connection’s special
knowledge of the data source to get at the data.

Free download pdf