Share via

VBA - SQL string referencing a Form Control in Where clause

Anonymous
2014-01-29T16:28:38+00:00

The following code works:

Dim rs As DAO.Recordset

Dim strSQL As String

strSQL = "Select * From [Table1] Where [Field1] = 17"

Set rs = CurrentDb.OpenRecordset (strSQL)

However, I need the numerical value in the Where clause to come from a form control and i can't seem to make this work.  I keep getting "Run-time error '3061': Too few parameters. Expected 1."

I've tried referencing it directly, through a variable, etc without luck:

strSQL = "Select * From [Table1] Where [Field1] = Forms![Form1]![Control1]"

I am sure that all of the field/control names are correctly spelled, etc.  What is the correct way to reference a form control value in such a Where clause?

Thanks!

Microsoft 365 and Office | Access | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous
2014-01-29T16:46:17+00:00

Hi,

DAO can't handle the form reference inside the SQL string. Concatenate the resulting value to the string:

strSQL = "Select * From [Table1] Where [Field1] = " & Forms![Form1]![Control1]

Was this answer helpful?

4 people found this answer helpful.
0 comments No comments

Answer accepted by question author

Anonymous
2014-01-29T16:44:09+00:00

Hi,

try with:

if Control1 is numeric

strSQL = "Select * From [Table1] Where [Field1] = " & Forms![Form1]![Control1]

if Control1 is a text

strSQL = "Select * From [Table1] Where [Field1] = '" & Forms![Form1]![Control1] & "'"

if Control1 is a data/time

strSQL = "Select * From [Table1] Where [Field1] = #" & Forms![Form1]![Control1] & "#"

Mimmo

Was this answer helpful?

4 people found this answer helpful.
0 comments No comments

0 additional answers

Sort by: Most helpful