执行保存的Access查询时出错,该查询依赖于表单中的参数值

时间:2016-02-16 20:10:55

标签: sql vba ms-access access-vba

我试图简单地打开一个查询并SELECT从中获取所有内容。该查询需要FROMTO个日期。我有frmA通过它将参数传递给查询。我打开frmA并输入2个日期。有趣的是,当我docmd.openQuery "qryInsurance"时,它会打开它而不会出现问题,但是,当我尝试Select * from qryInsurance时,它会告诉我它需要2个参数。

这是代码:

Public Function CountFollowup() As Boolean
On Error GoTo error_handler:
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim strsql As String
Dim rcount As Integer
Set DB = CurrentDb
CountFollowup = False

DoCmd.OpenQuery "qryInsurance"

strsql = "SELECT * FROM [qryInsurance];"

'CurrentDb.Execute "Delete * FROM temp_InsData"
Set rs1 = CurrentDb.OpenRecordset(strsql, , dbOpenSnapshot) ' here is where it gives me an ERROR, expecting 2 parameters when it OPENS it fine before strsql
Set rs2 = CurrentDb.OpenRecordset("temp_InsData")

Debug.Print strsql


Exit Function
error_handler:
MsgBox Err.Number & " - " & Err.Description
End Function

1 个答案:

答案 0 :(得分:3)

似乎 qryInsurance 包含对表单控件的引用,可能就像这样... Forms!frmA!From

使用DoCmd.OpenQuery时会解析这些引用,但使用DAO.Database.OpenRecordset方法时则不会。对于OpenRecordset,它们被解释为您尚未提供值的参数。

如果您打开查询的QueryDef,然后将每个参数Name提供给Eval(),它会为您提供这些表单控件的值...因此您可以将它们作为参数的值。

该描述可能并不容易理解,但代码非常简单。

Set db = CurrentDb ...

之前添加这些变量声明
Dim db As DAO.Database
Dim prm As DAO.Parameter
Dim qdf As DAO.QueryDef
Dim CountFollowup ' As what? Boolean?

然后......

Set db = CurrentDb
CountFollowup = False

'DoCmd.OpenQuery "qryInsurance"
'strsql = "SELECT * FROM [qryInsurance];"
'CurrentDb.Execute "Delete * FROM temp_InsData"

Set qdf = db.QueryDefs("qryInsurance")
For Each prm In qdf.Parameters
    prm.Value = Eval(prm.Name)
Next
'Set rs1 = CurrentDb.OpenRecordset(strsql, , dbOpenSnapshot) ' here is where it gives me an ERROR, expecting 2 parameters when it OPENS it fine before strsql
Set rs1 = qdf.OpenRecordset(dbOpenSnapshot)

' and the rest ...