tags:

views:

91

answers:

2

I am running a query from the VBA editor of Access:

select max(somerow) from sometable

I want to put the result of this query into a VBA variable. How do i do it?

+3  A: 

Look at Access Help for DMax function.

Dim varSomething As Variant
varSomething = DMax("somerow", "sometable")

Edit: I realize that suggestion is not what you were looking for. But it seems to me you may be taking the long way round to achieve something that is simple with the DMax domain function.

HansUp
+1  A: 

If you just want the Max value, you should consider using HansUps Solution.

Here is a solution using DAO:

Dim rs As DAO.Recordset
Dim sqlMax As String
Dim result As Integer

sqlMax = "select max(somerow) from sometable"
Set rs = CurrentDb.OpenRecordset(sqlMax)

If rs.Fields.Count = 1 Then
    result = rs.Fields(0)
End If

Set rs = Nothing

You will need to add a Reference to the Microsoft DAO Object library through Tools->References in the VBA Editor

marg
That reference will already be there for databases created in any version except 2000, unless somebody has removed it (which they shouldn't). Also, you don't even need the reference if you declare your recordset variable as type Object. The rest of it will work perfectly in that case even without the reference.
David-W-Fenton