VBA访问中的动态计算字段

时间:2017-06-22 20:46:38

标签: sql vba ms-access

我正在尝试将字段添加到现有表中。该字段使用两个变量'myPrice'计算,该变量是特定日期记录的价格,'previousPrice'是第一个记录中相同部分的价格,仅来自前一个月的价格。我正在使用循环来遍历整个价格记录集,从而每次都改变这两个变量。我的代码如下:

Function priceDifference()

Dim currentPrice As Currency
Dim previousPrice As Currency
Dim recordDate As Date
Dim previousDate As Date
Dim dbsASSP As DAO.Database
Dim priceTable As DAO.TableDef
Dim diffFld As DAO.Field2
Dim rstCurrentPrice As DAO.Recordset
Dim rstPreviousPrice As DAO.Recordset
Dim PN As String

Set dbsASSP = CurrentDb
strSQL = "SELECT * FROM qryPrice"
Set rstCurrentPrice = dbsASSP.OpenRecordset(strSQL, dbOpenDynaset)

Set priceTable = dbsASSP.TableDefs("tblPrice")
Set diffFld = priceTable.CreateField("Difference", dbCurrency)

If Not (rstCurrentPrice.EOF) Then
    rstCurrentPrice.MoveFirst
    Do Until rstCurrentPrice.EOF = True
        PN = rstCurrentPrice![P/N]
        recordDate = rstCurrentPrice![myDate]
        previousDate = Format(DateAdd("m", -1, recordDate), "M 1 YYYY")
        myPrice = rstCurrentPrice!Price
        strPreviousSQL = "SELECT * FROM qryPrice WHERE [MyDate] = #" & previousDate & "# AND [Type] = 'Net Price' AND [P/N] = " & PN & ""
        Set rstPreviousPrice = dbsASSP.OpenRecordset(strPreviousSQL, dbOpenDynaset)
        myCodeName = rstCurrentPrice!CodeName
        If DCount("[P/N]", "qryPrice", "[MyDate] = #" & previousDate & "# And [P/N] = " & PN) <> 0 Then
            previousPrice = rstPreviousPrice!Price
        Else
            previousPrice = myPrice
        End If

    rstCurrentPrice.MoveNext
    Loop
Else
    MsgBox "Finished looping through records."
End If

diffFld.Expression = myPrice - previousPrice

rstCurrentPrice.Close
rstPreviousPrice.Close

priceTable.Fields.Append diffFld

End Function

从语法上讲,它有效。然而,计算出的字段并没有给出正确的值,我无法弄清楚为什么,尽管我认为它与动态公式有关。

感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

您在代码中添加数字而不是公式时,您的代码无效,但您应该avoid calculated fields

使用查询:

SELECT 
    nPrice.[P/N], 
    nPrice.Price,  
    nPrice.MyDate,
    oPrice.MyDate,
    nPrice.Price-Nz(oPrice.Price,nPrice.Price) AS diff
FROM (
   SELECT 
       [P/N],
       Price, 
       MyDate, 
       Format(DateAdd("m",-1,MyDate),"yyyymm") as previousMonthYear
   FROM 
       tblPrice) AS nPrice 
LEFT JOIN (
    SELECT 
        [P/N], 
        Price, 
        MyDate,
        Format(MyDate,"yyyymm") AS monthYear 
    FROM 
        tblPrice)  AS oPrice 
ON 
    nPrice.[P/N] = oPrice.[P/N] 
    AND nPrice.previousMonthYear = oPrice.monthYear

这会计算差异动态,您无需存储它。

我假设每月最多只有一个价格,否则您需要过滤子查询或只计算之前的最后价格差异。 如果查询太慢([P / N]和MyDate需要索引),您仍然可以使用它来更新表tblPrice的字段,但每次更新或插入价格时都必须更新在tblPrice

答案 1 :(得分:1)

我认为您可以使用此查询来避免代码循环

SELECT A.qryPrice, A.MyDate, B.qryPrice, B.MyDate
FROM qryPrice A LEFT OUTER JOIN qryPrice B 
ON A.[P/N] = B.[P/N] 
AND B.MyDate = DATEADD(month, -1, A.MyDate)