Hello Everyone,
I need to create a field in a report that calculates the average of the last 5 records (from the [volume2009] field) in the report. The report is based on a query called qry_Daily_Volume. I figured the best way to do this would be to create a VBA function ("Last5DaysAvg")to move to the last record (MoveLast)of the dataset and then loop to sum up each of previous (MovePrevious) records, thus getting the total of the last 5 records and then dividing that by 5. The resulting number would then be displayed in the footer of a report which lists daily volume to show the average of the last 5 records.
Unfortunately my function does not seem to work, and I believe the problem is with defining a record set.
Here is the code I have so far, which does not work:
Function CalcLastFive() As Double
Dim result As Double
result = 0
Dim intI, rs As DAO.Recordset
intI = 1
Set rs = db.OpenRecordset("qry_daily_volume", dbOpenDynaset)
MoveLast
Do
If intI > 5 Then Exit Do
result = result + Volume2009
intI = intI + 1
MovePrevious
Loop
result = result / 5
CalcLastFive = result
End Function
Thanks in advance for taking a look at this issue, I would greatly appreciate any input from this wonderful forum
All the best,
Ben
I need to create a field in a report that calculates the average of the last 5 records (from the [volume2009] field) in the report. The report is based on a query called qry_Daily_Volume. I figured the best way to do this would be to create a VBA function ("Last5DaysAvg")to move to the last record (MoveLast)of the dataset and then loop to sum up each of previous (MovePrevious) records, thus getting the total of the last 5 records and then dividing that by 5. The resulting number would then be displayed in the footer of a report which lists daily volume to show the average of the last 5 records.
Unfortunately my function does not seem to work, and I believe the problem is with defining a record set.
Here is the code I have so far, which does not work:
Function CalcLastFive() As Double
Dim result As Double
result = 0
Dim intI, rs As DAO.Recordset
intI = 1
Set rs = db.OpenRecordset("qry_daily_volume", dbOpenDynaset)
MoveLast
Do
If intI > 5 Then Exit Do
result = result + Volume2009
intI = intI + 1
MovePrevious
Loop
result = result / 5
CalcLastFive = result
End Function
Thanks in advance for taking a look at this issue, I would greatly appreciate any input from this wonderful forum
All the best,
Ben