无效的参数错误:MSAccess和SQL

Bio*_*ard 0 ms-access vba access-vba

我试图从MSAccess访问我的SQL数据库中的某些行,并且我在此行上不断收到无效的参数错误:

Set rs = CurrentDb.OpenRecordset("SELECT TimeID " & _
    "FROM tblLunchTime " & _
    "WHERE ProductionID = prodSelect AND EndTime is NULL AND StartTime < dateAdd('h', 3, NOW())", [dbSeeChanges])
Run Code Online (Sandbox Code Playgroud)

这不对吗?

Private Sub cmdClockEnd_Click()

'Check if a group has been selected.
If frmChoice.value = 0 Then

    MsgBox "Please select a production line."

    End

End If

'Setup form for user input.
lblEnd.Visible = True

'Save end of lunch value.
lblEnd.Caption = Format(Now, "MMM/DD/YY hh:mm:ss AMPM")

'Declare database variables.
Dim dbName As DAO.Database
Dim strValuesQuery As String
Dim rs As DAO.Recordset
Dim prodSelect As String
Dim sSQL As String
Dim timeValue As String
Set dbName = CurrentDb

'Get values of Production Line.
If frmChoice.value = 1 Then

prodSelect = "L2"

ElseIf frmChoice.value = 2 Then

prodSelect = "L3"

End If

'Get the last TimeID with the following parameters.
sSQL = "SELECT TimeID " & _
    "FROM tblLunchTime " & _
    "WHERE ProductionID = prodSelect AND EndTime is NULL AND StartTime < #" & DateAdd("h", 3, Now()) & "#"

Set rs = dbName.OpenRecordset(sSQL, dbSeeChanges)

strValuesQuery = _
                    "UPDATE tblLunchTime " & _
                    "SET EndTime = '" & Now & "'" & _
                    "WHERE TimeID = " & rs![TimeID] & " "

'Turn warning messages off.
DoCmd.SetWarnings False

'Execute Query.
DoCmd.RunSQL strValuesQuery

'Turn warning messages back on.
DoCmd.SetWarnings True

End Sub
Run Code Online (Sandbox Code Playgroud)

Fio*_*ala 5

你需要把prodSelect放在引号之外:

"WHERE ProductionID = " & prodSelect & " AND ...
Run Code Online (Sandbox Code Playgroud)

几乎总是最好说:

sSQL="SELECT TimeID " & _
    "FROM tblLunchTime " & _
    "WHERE ProductionID = " & prodSelect & _
    " AND EndTime is NULL AND StartTime < dateAdd('h', 3, NOW())"
''Debug.print sSQL
Set rs = CurrentDb.OpenRecordset(sSQL)
Run Code Online (Sandbox Code Playgroud)

您可以看到使用Debug.Print的优势.

AHA prodSelect是文字!你需要报价!

sSQL="SELECT TimeID " & _
    "FROM tblLunchTime " & _
    "WHERE ProductionID = '" & prodSelect & _
    "' AND EndTime is NULL AND StartTime < dateAdd('h', 3, NOW())"
Run Code Online (Sandbox Code Playgroud)

  • 这似乎也有效:设置rs = CurrentDb.OpenRecordset(sSQL,options:= dbSeeChanges) (2认同)