使用变量来设置rst

时间:2014-07-25 14:50:28

标签: access-vba

我正在尝试使用SQL字符串打开记录集。我得到运行时错误3061“太少的参数。”任何帮助将不胜感激。

Dim stAppName As String
Dim stURL As String
Dim rst As Recordset
Dim dbs As Database
Dim stringToSearch As Integer
Dim strSQL As String

Set dbs = CurrentDb


stringToSearch = InputBox("What is your route #?", "Enter route #: ")


strSQL = "SELECT ESRP.* FROM ESRP WHERE ESRP.Route=stringToSearch"

Set rst = dbs.OpenRecordset(strSQL)

2 个答案:

答案 0 :(得分:0)

请按照以下方式更改strSQL的代码行,如Fionnuala所示,您需要在引号之外使用变量。

假设Route字段是Text数据类型,我们需要为字符串放单引号,如果它的数字没有单引号,则为#而不是单引号的日期

strSQL = "SELECT ESRP.* FROM ESRP WHERE ESRP.Route='" & stringToSearch & "'"

答案 1 :(得分:0)

这是一个小样本,也许它可以帮助你

Public Function fn_SQL_dbOpenRecordset(Optional vsql As String = "") As Recordset

    Dim dbs       As DAO.Database 

    Dim rs As Recordset
    On Error GoTo END_CODE

    'Set the database
    Set dbs = CurrentDb
    Set rs = dbs.OpenRecordset(vsql, dbOpenForwardOnly) 'you can use: dbOpenDynamic; dbOpenSnapshot; dbOpenTable

    Set fn_SQL_dbOpenRecordset = rs

    Exit Function

END_CODE:
    Set fn_SQL_dbOpenRecordset = Nothing
End Function


Public Sub Program_Test()

    On Error GoTo ERROR_SUB
    Dim rs As Recordset
    Dim sName As String


    sName = "Joe"
    sName = "'" & sName & "'" 'WARNING: BE CAREFUL WITH SQL INJECTION !!! Google it

    Set rs = fn_SQL_dbOpenRecordset("select * from  table1 d where PersonName = " & sName)

    Dim i As Long
    i = 0

    While Not rs.EOF
      Debug.Print rs(0).Value & " - " & rs(1).Value
      rs.MoveNext
    Wend

ERROR_SUB:

     On Error Resume Next
     If Not rs Is Nothing Then rs.Close
     Set rs = Nothing
End Sub