2017-06-22 55 views
3

我試圖將字段添加到現有表中。該字段使用兩個變量「myPrice」(它是特定日期的記錄價格)和'previousPrice'計算得出,它是第一條記錄中相同部分的價格,僅爲前一個月的a。我使用循環遍歷整個價格記錄集,從而每次更改兩個變量。我的代碼如下:VBA訪問中的動態計算字段

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 

在句法上,它的工作原理。然而,計算的字段並不能給我正確的值,我不知道爲什麼,儘管我認爲它與動態公式有關。

任何幫助表示讚賞。謝謝!!

回答

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

+0

@布賴恩邁克爾避免你的代碼迴路,我如果代碼本身正確與否未得到驗證,但是這絕對是你要使用的方法。看這裏。 – SandPiper

+0

@BitAccesser 感謝您的幫助!這最終使我走上了正確的道路,我能夠調整上面的代碼並解決問題。 –

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)