问题
I'm trying to run some SQL commands in Access VBA to update the blank (null) fields in a column with the value obtained from a combobox in the form.
At the moment I'm receiving
Run time Error '3061' Too Few Parameters. Expected 1
but it appears to be properly formed.
The code I'm using is below. User will be passed as a string, e.g. - "Joe Bloggs".
Public Sub testSub(user as string)
Dim db as DAO.Database
Dim sqlstr as String
set db as CurrentDB
sqlstr = "UPDATE tTable1 SET Field1 = [" & user & "] WHERE Field1 IS NULL;"
db.Execute sqlstr
End Sub
回答1:
I think you need to have user as a 'string'
in your query using single quotes. Also, I have always used set db = currentdb
instead of using as
Public Sub testSub(user as string)
Dim db as DAO.Database
Dim sqlstr as String
set db = CurrentDB
sqlstr = "UPDATE tTable1 SET Field1 = '" & user & "' WHERE Field1 IS NULL;"
db.Execute sqlstr
End Sub
EDIT: As @jarlh has mentioned I agree, I don't think that the square parentheses are required
回答2:
Consider a parameter query instead of concatenating a quoted string value into your UPDATE
statement text. You don't need those quotes when using the parameter approach, and that also safeguards you from the issue Alex warned about (when the user string itself contains an apostrophe).
Public Sub testSub(ByVal pUser As String)
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim sqlstr As String
sqlstr = "UPDATE tTable1 SET Field1 = [which_user] WHERE Field1 IS NULL;"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, sqlstr)
qdf.Parameters("which_user").Value = pUser
qdf.Execute sqlstr, dbFailOnError
End Sub
来源:https://stackoverflow.com/questions/36453949/update-null-fields-with-sql-in-ms-access