Running / Rolling Sum

T

Tiffany

I used Article 205183 to create a running sum within my
query. It works the first time I run it, however, each
additional time I open the query, I get different
results. It is almost as if it adds the results to the
last amount it came up with in the running sum. I am not
very familiar with modules so any help that can be
provided will be greatly appreciated. Thanks.

Article 205183:

Query: qryGrpRunSum
-------------------
Type: Select Query

Field: CategoryID
Table: Products
Sort: Ascending

Field: UnitsInStock
Table: Products

In the Field row of the third column in the query design
grid, type the following expression:RunSum: fncRunSum
([CategoryID], [UnitsInStock])

Save the query as qryGrpRunSum, and then close the query.
Create a new module, and then type or paste the following
code:Option Compare Database
Option Explicit

Function fncRunSum(lngCatID As Long, lngUnits As Long) As
Long
'Variables that retain their values.
Static lngID As Long
Static lngAmt As Long

If lngID <> lngCatID Then
'If the current ID does not match the last ID,
then (re)initialize.
lngID = lngCatID
lngAmt = lngUnits
Else
'If the current ID matches the last, keep a
running sum for the ID.
lngAmt = lngAmt + lngUnits
End If

'Pass the running sum back to the query.
fncRunSum = lngAmt
End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top