我试图用这个 Excel 字段模拟 MS-Excel 公式:A - StudyYears B - Inflation_Adjusted_Expenditures C - AnnualContribution D - ContributionIncrease E - InterestIncome F - RunningBalance
当前 Excel 光标位置:列 - F,行 - 3 公式:F2+E2+C2+B2
到 MS-Access sql 查询。从不同表中获取的字段。但是字段 RunningBalance 最初取自表 tblParameter 字段 StartingBalance。此查询的下一个 RunningBalance 记录应该是从上一个记录中添加四个字段。
由于循环引用是 sql 查询中的一个问题,我尝试创建一个这样的函数。
'*************************************************************
' FUNCTION: PREV_RUNNINGBALANCE()
' PURPOSE: Retrieve a value from a field in the previous record.
' PARAMETERS:
' StartingBalance - Starting Running Balance which is given
' RefValue - ID value
' RETURN: The computed value for the 4 field mention located in the
' previous record.
' EXAMPLE:
' =Prev_RunningBalance(StudyYears, 404585)
'**************************************************************
Function Prev_RunningBalance(RefValue As Long, StartingBalance As Long)
Dim dbs As DAO.Database
Dim rsSQL As DAO.Recordset
Dim strSQL As String
Dim vRunningBalance As Integer
On Error GoTo Err_PrevRecVal
strSQL = "Select Inflation_Adjusted_Expenditures, AnnualContribution, InterestIncome, RunningBalance FROM GenerateFundingPlanData WHERE StudyYears = " & RefValue
Set dbs = CurrentDb
Set rsSQL = db.OpenRecordset(strSQL, dbOpenDynaset)
rsSQL.FindFirst "StudyYears = " & RefValue
If Not rsSQL.NoMatch Then
'Return 0
Prev_RunningBalance = 0
End If
If rsSQL.BOF Then
Prev_RunningBalance = 0
'Prev_RunningBalance = rsSQL![Inflation_Adjusted_Expenditures] + rsSQL![AnnualContribution] + rsSQL![InterestIncome] + StartingBalance
End If
Do While Not rsSQL.BOF
' Move to the previous record.
rsSQL.MovePrevious
' Sum the fields to get the RunningBalance
' RunningBalance = Inflation_Adjusted_Expenditures + AnnualContribution + InterestIncome + CurrentRunningBalance
Prev_RunningBalance = rsSQL![Inflation_Adjusted_Expenditures] + rsSQL![AnnualContribution] + rsSQL![InterestIncome] + rsSQL![RunningBalance]
Loop
'Close Connection
rsSQL.Close
Bye_PrevRecVal:
Set rsSQL = Nothing 'Deassign all objects.
Set dbs = Nothing
Exit Function
Err_PrevRecVal:
Resume Bye_PrevRecVal
End Function
尝试该功能后,我得到一个空结果。这是我的查询示例。
SELECT Prev_RunningBalance(a.StudyYears, 404585) as RunningBalance,
a.StudyYears FROM AnalysisYears a;
我是否使用了正确的功能?
请指出我。谢谢你。