recordset.find using variable VBA ADODB

l.wach picture l.wach · Jan 16, 2017 · Viewed 8.3k times · Source

I am getting pretty desperate trying to get this trivial search to work:

 rst2.Find "ID = '" & messID & "'"

I have tried just about any combination but it just never returns a search result. the whole code would be here:

Option Compare Database
Option Explicit

'Modul zum Updaten des Status eines Messmittels in der Stammdatenbank (Entnommen/Verfügbar)3

Public Function updateStatus()

Dim rst2 As ADODB.Recordset
Dim rst As ADODB.Recordset
Dim messID As String

Set rst = New ADODB.Recordset 'Stammdaten zur Bearbeitung öffnen
            rst.ActiveConnection = CurrentProject.AccessConnection
            rst.CursorType = adOpenKeyset
            rst.LockType = adLockOptimistic
            rst.Open "Stammdaten"
            rst.MoveFirst

Set rst2 = New ADODB.Recordset 'zur Bearbeitung öffnen
            rst2.ActiveConnection = CurrentProject.AccessConnection
            rst2.CursorType = adOpenKeyset
            rst2.LockType = adLockOptimistic
            rst2.Open "Verwendung"

Do While Not rst.EOF
            messID = rst!ID
            Debug.Print messID
            rst2.Find "ID = '" & messID & "'"
            If rst2.EOF = True Then 'Falls nicht vorhanden
                Debug.Print "Keine Verwendung gefunden!"
            Else
                rst2.Sort = "Nr DESC"
                rst2.MoveFirst
                Debug.Print rst2!Status
            End If
            rst.MoveNext
Loop
rst.Close
rst2.Close

End Function

What am I missing? I literally tried hunderds of diffrent search strings :(

Answer

A.S.H picture A.S.H · Jan 16, 2017

You have a table-type recordset and you're searching it by the key. This is the typical use-case for the Seek method instead of the Find method.

According to this: https://support.microsoft.com/en-us/kb/108149

The find methods (FindFirst, FindLast, FindNext, and FindPrevious) apply to Dynasets and Snapshots but not to Table objects. Conversely, the Seek method is available only on the Table object.

Although that page seems focused on DAO more than ADO, but the same logic should apply to both cases.

I think you should try the Seek method https://msdn.microsoft.com/en-us/library/ms675109(v=vs.85).aspx

rst2.Seek "=", messID
If rst2.NoMatch Then ' not found ...