This example uses the Recordset object's Seek method and Index property in conjunction with a given Employee ID, to locate the employee's name in the Employees table of the Nwind.mdb database.
'BeginSeekVB
Public Sub SeekX()
' To integrate this code replace the data source
' in the connection string
'recordset and connection variables
Dim rstEmployees As ADODB.Recordset
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim strSQLEmployees As String
Dim strID As String
Dim strPrompt As String
strPrompt = "Enter an EmployeeID (e.g., 0 to 9)"
' Open connection
Set Cnxn = New ADODB.Connection
strCnxn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=c:\Program Files\Microsoft Office\Office\Samples\northwind.mdb;" & _
"user id=admin;password=;"
Cnxn.Open strCnxn
' open recordset server-side for indexing
Set rstEmployees = New ADODB.Recordset
rstEmployees.CursorLocation = adUseServer
strSQLEmployees = "employees"
rstEmployees.Open strSQLEmployees, strCnxn, adOpenKeyset, adLockReadOnly, adCmdTableDirect
' Does this provider support Seek and Index?
If rstEmployees.Supports(adIndex) And rstEmployees.Supports(adSeek) Then
rstEmployees.Index = "PrimaryKey"
' Display all the employees
rstEmployees.MoveFirst
Do While rstEmployees.EOF = False
Debug.Print rstEmployees!EmployeeId; ": "; rstEmployees!firstname; " "; _
rstEmployees!LastName
rstEmployees.MoveNext
Loop
' Prompt the user for an EmployeeID between 0 and 9
rstEmployees.MoveFirst
Do
strID = LCase(Trim(InputBox(strPrompt, "Seek Example")))
' Quit if strID is a zero-length string (CANCEL, null, etc.)
If Len(strID) = 0 Then Exit Do
If Len(strID) = 1 And strID >= "0" And strID <= "9" Then
rstEmployees.Seek Array(strID), adSeekFirstEQ
If rstEmployees.EOF Then
Debug.Print "Employee not found."
Else
Debug.Print strID; ": Employee='"; rstEmployees!firstname; " "; _
rstEmployees!LastName; "'"
End If
End If
Loop
End If
' clean up
rstEmployees.Close
Set rstEmployees = Nothing
Cnxn.Close
Set Cnxn = Nothing
End Sub
'EndSeekVB
Index Property | Recordset Object | Seek Method
© 1998-2001 Microsoft Corporation. All rights reserved.