如何将参数查询中输入的值存储在声明的变量中?

时间:2014-09-05 10:08:45

标签: sql vba ms-access

我想将用户在参数查询中输入的值存储到声明的变量中;我怎么能这样做?

例如:

Dim storeHere as Integer

// other vba statements

stmnt = //other sql statements

        "WHERE [Student].[Class] = [Enter Class:] " & _

        // other sql statements

所以我想存储用户在变量storeHere中作为类输入的值。 我怎样才能做到这一点。请帮忙。  注意:我正在使用访问

1 个答案:

答案 0 :(得分:2)

假设您在Access中有一个已保存的查询,名为[getStudentsByClass]

PARAMETERS [Enter Class:] Short;
SELECT Student.*
FROM Student
WHERE (((Student.Class)=[Enter Class:]));

如果以交互方式运行它,将提示“输入类:”,然后显示相应的结果。如果要从VBA代码运行该查询,则需要首先提示输入参数值,然后通过QueryDef对象运行查询

Dim storeHere As Integer
Dim cdb As DAO.Database, qdf As DAO.QueryDef, rst As DAO.Recordset

storeHere = InputBox("Enter class:", "Enter Parameter Value")
Set cdb = CurrentDb
Set qdf = cdb.QueryDefs("getStudentsByClass")
qdf![Enter Class:] = storeHere
Set rst = qdf.OpenRecordset(dbOpenSnapshot)

' Do what you want with the returned records. For demo purposes:
Debug.Print rst.RecordCount & " record(s) returned."

rst.Close
Set rst = Nothing
Set qdf = Nothing
Set cdb = Nothing