
Originally Posted by
NISMOJim
Hello,
I'm trying to figure out code to run a query to return the sum of a field between a date range, and am having little luck with it. Here's what I have so far;
strSQLLastTotal = "Select Quantity AS SumOfQuantity FROM Transactions WHERE Date between " & LastDateStart & " And " & LastDateEnd
DoCmd.RunSQL strSQLLastTotal

Originally Posted by
NISMOJim
I'm not sure how it all works, but isn't there a way to run the SQL then save it as a recordset?
Nope....
From Help:
You can use the RunSQL action to run a Microsoft Access
action query by using the corresponding SQL statement.
So an action query is an Append, Delete, Make-table or an Update query. A "SELECT" query cannot be executed using "DoCmd.RunSQL".

Originally Posted by
JoeM
One way would be to create the query code (like you have), assign it to a query (using "CurrentDB.QueryDefs(myQueryName).SQL=strSQLLastTotal")
What JoeM is telling you:
Create a query
In the grid, add the table "Transactions"
Add the field "Quantity".
Save the query - lets call it "CalcQuanity".
This is now a saved query.
In your code, (BTW - dates need delimiters I added them)
Code:
strSQLLastTotal = "Select Sum(Quantity) AS SumOfQuantity FROM Transactions WHERE Date between #" & LastDateStart & "# And #" & LastDateEnd & "#"
CurrentDB.QueryDefs("CalcQuanity").SQL=strSQLLastTotal
The SQL of the saved query "CalcQuanity" has been changed from the simple select string to the totals query SQL.
Now , using DLOOKUP(), you can get the value from the saved query "CalcQuanity".
In the code, you would have a line something like:
Code:
SomeVariable = DLOOKUP("SumOfQuantity", "CalcQuanity")
-------------------------------------
Another way would be to open a recordset in code (VBA).
(Warning - air code)
Code:
Dim r as DAO.Recordset
Dim strSQLLastTotal as String
.
.
.
.
.
strSQLLastTotal = "Select Sum(Quantity) AS SumOfQuantity FROM Transactions WHERE Date between #" & LastDateStart & "# And #" & LastDateEnd & "#;"
Set r = Currentdb.OpenRecordset(ssql)
'check for records
If Not (r.BOF and r.EOF) Then
LastTotal = r("SumOfQuantity")
Else
LastTotal = 0
End If
.
.
.
.
r.close
Set r = nothing