Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Result of a SQL query to a variable in VBA code?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
How could I place the result of a SQL query/statement to a variable by using VBA?

The sql statement would be something like this:
Code:
SELECT Max([Field2]) AS MaxValue
FROM Table1
WHERE Field1 = 'match';

And the variable.. :
Code:
Dim varResult As Variant


I would be very grateful if somebody could help me with this.
 
You can use something like...

Dim db As Database
Dim rst As Recordset
Dim strSQL As String
Dim intResult As Integer

strSQL = "SELECT Max(fldOne) AS MaxValue FROM tblOne;"
Set db = CurrentDb
Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)

rst.MoveFirst
intResult = rst!MaxValue
rst.Close

This assumes that the SQL only returns one value, which obviously it true if you're using Max. There are two ways to write error-free programs; only the third one works.
 
Thank you, GHolden!! You saved my day (and maybe the whole week)!

I needed to change
Code:
Dim rst As Recordset
to
Code:
Dim rst As DAO.Recordset

After that it started to work just like I hoped it would work.
 
Alternatively you could use the Domain Lookup functions, such as Dmax, Dlookup etc...

Code:
intResult = Dmax("Field2","Table1","[Field1]=" & match)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top