将参数传递给查询Access VBA

时间:2016-10-18 17:09:56

标签: ms-access

之前已经问过这个问题。我根据我对该主题研究的理解调整了我的代码(下面)。但是,我的代码在下面以粗体显示在线。

我有一个表单(PBCIncSum),用户可以在其中输入查询RstName的开始日期和结束日期条件。此函数用于计算查询RstName中数据的第95百分位值。当我运行代码时,我得到一个运行时错误'3061:参数太少。预期2.我做错了什么?花了三天没有任何解决方案盯着这段代码。

Public Function PercentileRst(RstName As String, fldName As String, PercentileValue As Double) As Double
 'This function will calculate the percentile of a recordset.
 'The field must be a number value and the percentile has to
 'be between 0 and 1.
 If PercentileValue < 0 Or PercentileValue > 1 Then
    MsgBox "Percentile must be between 0 and 1", vbOKOnly
 End If
 Dim PercentileTemp As Double
 Dim dbs As DAO.Database
 Set dbs = CurrentDb
 Dim xVal As Double
 Dim iRec As Long
 Dim i As Long
 Dim RstOrig As DAO.Recordset
 Dim qdf As DAO.QueryDef
 Dim prm As DAO.Parameter

 Set qdf = dbs.QueryDefs(RstName)
 qdf.Parameters(0) = Forms!PBCIncSum!StDate
 qdf.Parameters(1) = Forms!PBCIncSum!EndDate

 For Each prm In qdf.Parameters
      prm = Eval(prm.Name)
 Next prm

 **Set RstOrig = CurrentDb.OpenRecordset(RstName, dbOpenDynaset)**
 RstOrig.Sort = fldName
 Dim RstSorted As DAO.Recordset
 Set RstSorted = RstOrig.OpenRecordset()
 RstSorted.MoveLast
 RstSorted.MoveFirst
 xVal = ((RstSorted.RecordCount - 1) * PercentileValue) + 1
 'x now contains the record number we are looking for.
 'Note x may not be     whole number
 iRec = Int(xVal)
 xVal = xVal - iRec
 'i now contains first record to look at and
 'x contains diff to next record
 RstSorted.Move iRec - 1
 PercentileTemp = RstSorted(fldName)
 If xVal > 0 Then
    RstSorted.MoveNext
    PercentileTemp = ((RstSorted(fldName) - PercentileTemp) * xVal) + PercentileTemp
 End If
 RstSorted.Close
 RstOrig.Close
 Set RstSorted = Nothing
 Set RstOrig = Nothing
 Set dbs = Nothing
 Set qdf = Nothing
 PercentileRst = PercentileTemp

结束功能

1 个答案:

答案 0 :(得分:1)

  

我做错了什么?

您正尝试使用CurrentDb.OpenRecordset来运行查询。您已创建QueryDef对象qdf并定义了其参数,因此您需要使用该QueryDef对象的OpenRecordset方法:

Set rstOrig = qdf.OpenRecordset