2

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
2
  • 2
    Why those square brackets? Doesn't that imply a column name in this case? Commented Apr 6, 2016 at 14:30
  • 4
    Take care for Jim O'Shea Commented Apr 6, 2016 at 14:30

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.