How to check if a recordset is empty (or get the count of records) and to get summary values (e.g. max, min, avg) (1 Viewer)

tcneo

Member
Local time
Tomorrow, 00:29
Joined
Dec 7, 2021
Messages
68
Hi,

How do I check the following in a recordset (which is from a query, not a table):
1) if it is empty
2) number of records inside it (if i open the recordset with dbOpenDynaset)
3) max, min, avg

I get a type mismatch error if I try the following to get the max:

Code:
    Dim myR As Recordset
    Set myR = CurrentDb.OpenRecordset("Query1")
    MsgBox DSUm("Record_value", myR)
 

June7

AWF VIP
Local time
Today, 08:29
Joined
Mar 9, 2014
Messages
5,466
Can't use domain aggregate function on a recordset. DSum() should error as well. Recordset is not needed.

MsgBox DSum("Record_value", "Query1")
 

Pat Hartman

Super Moderator
Staff member
Local time
Today, 12:29
Joined
Feb 19, 2002
Messages
43,233
You can create a query of the query that does all the aggregate functions at once:

Select Dept, Sum(Expenses) As SumExpenses, Avg(Expenses) As AvgExpenses, Min(Expenses) As MinExpenses, .....
From YourQuery
 

LarryE

Active member
Local time
Today, 09:29
Joined
Aug 18, 2021
Messages
581
DCount("*","Query1") will give you the record count in Query1 So:
Code:
If DCount("*","Query1") > 0 Then
    Do This
Else
    MsgBox "There are no records"
End If
 

CJ_London

Super Moderator
Staff member
Local time
Today, 17:29
Joined
Feb 19, 2013
Messages
16,610
for recordsets

1) either check for EOF (rs.EOF) when rs is first opened (if EOF =true then no records) or .movelast and .recordcount
2) use ,movelast then check .recordcount
3) max, min, avg - don't understand this one
 

Pat Hartman

Super Moderator
Staff member
Local time
Today, 12:29
Joined
Feb 19, 2002
Messages
43,233
And don't forget to count the records:) ONE query does it all rather than multiple domain functions.

Select Dept, Sum(Expenses) As SumExpenses, Avg(Expenses) As AvgExpenses, Min(Expenses) As MinExpenses, ....., Count(*) As RecCount
From YourQuery
Group by Dept;
 
Last edited:

June7

AWF VIP
Local time
Today, 08:29
Joined
Mar 9, 2014
Messages
5,466
If include Dept or any non-aggregate calc fields in SELECT, need GROUP BY.

Then you pull value from query:

If Not myR.EOF Then
MsgBox = Nz(myR!SumExpenses, 0)
End If
 
Last edited:

Users who are viewing this thread

Top Bottom