In Access 2002, I have created a Make Table query to add a new field “Base$” through a custom function, moving average, that averages each 8 weeks of data. However, I also need to calculate a different result if there is an entry “X” in the Flag field--where there is a Flag "X", I want to duplicate the 8-week average number of the previous record. What is the VBA code to provide that alternate result? Here is a sample of the data, followed by the custom function.
ID WkEnd ItemNbr Sales$ Flag
464 9/3/05 Item1 22397
527 9/10/05 Item1 21742
591 10/22/05 Item1 22392
649 9/17/05 Item1 21581
715 9/24/05 Item1 21747
780 10/1/05 Item1 21424 X
845 10/8/05 Item1 21477
910 10/15/05 Item1 23806
984 10/29/05 Item1 22927
1049 11/5/05 Item1 33252 X
1114 11/12/05 Item1 20768
1179 11/19/05 Item1 20247
1447 12/17/05 Item1 26336
1513 12/24/05 Item1 32947
1583 12/31/05 Item1 20829
1651 9/3/05 Item2 23097
1719 9/10/05 Item2 44363 X
1835 10/22/05 Item2 38518
1902 9/17/05 Item2 32232
1970 9/24/05 Item2 32468
2036 10/1/05 Item2 41633 X
2105 10/8/05 Item2 27651
2174 10/15/05 Item2 26819
ID WkEnd ItemNbr Sales$ Flag
464 9/3/05 Item1 22397
527 9/10/05 Item1 21742
591 10/22/05 Item1 22392
649 9/17/05 Item1 21581
715 9/24/05 Item1 21747
780 10/1/05 Item1 21424 X
845 10/8/05 Item1 21477
910 10/15/05 Item1 23806
984 10/29/05 Item1 22927
1049 11/5/05 Item1 33252 X
1114 11/12/05 Item1 20768
1179 11/19/05 Item1 20247
1447 12/17/05 Item1 26336
1513 12/24/05 Item1 32947
1583 12/31/05 Item1 20829
1651 9/3/05 Item2 23097
1719 9/10/05 Item2 44363 X
1835 10/22/05 Item2 38518
1902 9/17/05 Item2 32232
1970 9/24/05 Item2 32468
2036 10/1/05 Item2 41633 X
2105 10/8/05 Item2 27651
2174 10/15/05 Item2 26819
Code:
Function MovAvg(ItemNbr, startDate, period As Integer)
Dim rst As DAO.Recordset
Dim sql As String
Dim ma As Currency
Dim n As Integer
sql = "Select * from tblSalesData "
sql = sql & "where ItemNbr = '" & ItemNbr & "'"
sql = sql & " and WkEnd <= #" & startDate & "#"
sql = sql & " order by WkEnd"
Set rst = CurrentDb.OpenRecordset(sql)
rst.MoveLast
For n = 0 To period - 1
If rst.BOF Then
MovAvg = 0
Exit Function
Else
ma = ma + rst.Fields("Sales$")
End If
rst.MovePrevious
Next n
rst.Close
MovAvg = ma / period
End Function
Comment