Article ID: 146909
Article Last Modified on 7/13/2004
Dim ds As Recordset
Set ds = MyDB.OpenRecordset("Employees", dbOpenDynaset)
ds.FindFirst "NameField = Text1.Text" ' This code is incorrect.
This code is trying to create a dynaset that finds the first occurrence of
the contents of Text1 in a field called NameField. Although the code does
not produce an error, it does not find the desired value. It searches
for the first occurrence of the string "Text1.Text" not the value of the
Text1.Text control property.
Dim ds As Recordset
Set ds = MyDB.OpenRecordset("Employees", dbOpenDynaset)
ds.FindFirst "NameField = '" & Text1.Text & "'"
The ampersand (&) operator concatenates the strings together correctly.
Also, in SQL syntax, you need to enclose string data in single quotation
marks to differentiate strings from variables.
Dim ds As Recordset
Dim SQL$ as String
Set ds = MyDB.OpenRecordset("Employees", dbOpenDynaset)
SQL$ = "NameField = '" & Text1.Text & "'"
Debug.Print SQL$
ds.FindFirst SQL$
If Text1 contains the string "Wilson," the Debug windows displays:
NameField = 'Wilson'If the data type of a field is a number instead of a string, do not enclose the value being sought in single quotation marks. For example, use the following code to create a dynaset that finds the first occurrence of a zip code in a field called ZipCodeField where the ZipCodeField data type is not a string:
Dim ds As Recordset
Dim SQL$ as String
Dim ZipCodeVar as Double
Set ds = MyDB.OpenRecordset("Employees", dbOpenDynaset)
ZipCodeVar = 98052
SQL$ = "ZipCodeField = " & ZipCodeVar ' This line builds the string.
Debug.Print SQL$
ds.FindFirst SQL$
Additional query words: pitfall RecordSource kbVBp400
Keywords: kbhowto KB146909