1

I have a Combo Box (cbo1) that list available Items. When I select an item in cbo1, I would like it change a checkbox to True (or Yes).

cbo1 gets data from tblLOG where Box (checkbox) is NO Query

I've tried using

UPDATE tblLOG 
Set Box = True
WHERE Serial = cboSerial

Actual Code.

Private Sub cbo1_Change()
    Dim strSQL As String
    Dim i As Integer
    Dim Msg As String
    Dim Assm As String

    Assm = cbo1.Value

    'Exit this sub if the combo box is cleared
    Msg = "Make Update" & vbCr & vbCr

    i = MsgBox(Msg, vbQuestion + vbYesNo, "UPDATE VALUE?")
    If i = vbYes Then
        strSQL = "UPDATE tblLOG " _
        & "SET Box= True " _
        & "WHERE Serial = Assm;"
        CurrentDb.Execute strSQL, dbFailOnError
        Response = acDataErrAdded
    End If
End Sub

My Results are

Run-time error '3061': Too few parameters. Expected 1.

4

1 回答 1

1

The reason for your error is because you are not evaluating your VBA variable Assm, but rather concatenating the string "Assm" to your SQL query.

strSQL = "UPDATE tblLOG " _
& "SET Box= True " _
& "WHERE Serial = Assm;"

If you were to Debug.Print the variable strSQL to the console, you would see the string:

"UPDATE tblLOG SET Box= True WHERE Serial = Assm;"

However, since Assm is not a string in the SQL query (i.e. it is not surrounded by single or double quotes), it is interpreted as a parameter whose value hasn't been supplied when the SQL query is subsequently executed.


To solve this, you could concatenate the evaluated value of the Assm variable, e.g.:

strSQL = "UPDATE tblLOG " _
& "SET Box= True " _
& "WHERE Serial = '" & Assm & "';"

This assumes that Serial is a text field - if this is not the case, remove the single quotes from the above.

Your entire code could be condensed somewhat to:

Private Sub cbo1_Change()
    If MsgBox("Make Update", vbQuestion + vbYesNo, "UPDATE VALUE?") = vbYes Then
        CurrentDb.Execute "update tbllog set box = true where serial = '" & cbo1 & "';", dbFailOnError
        Response = acDataErrAdded
    End If
End Sub

Though, this is still open to SQL injection, and so a better practice is to parameterise the query, e.g.:

With CurrentDb.CreateQueryDef("", "update tbllog t set t.box = true where t.serial = myserial;")
    .Parameters!myserial = cbo1
    .Execute
End With
于 2019-05-28T20:54:34.753 回答