VBA SQL using a variable in sql query

exaccess

Registered User.
Local time
Today, 08:45
Joined
Apr 21, 2013
Messages
287
What is wrong with this statement.

Code:
"SELECT * FROM [TransTbl] WHERE [TransTbl].[Assoc] = & 'InAssoc' & " & _
       "ORDER BY [TransTbl].[LastName]"

TransTbl is the table on which the query will run.

Assoc and LastName are fields of the table. InAssoc is defined text variable which can change each time the query is executed Please help.
 
You need to concatenate the strings with the variables. I've not done this over two lines so would do
Code:
strSQL = "SELECT * FROM [TransTbl] WHERE [TransTbl].[Assoc] = '" & InAssoc & "'" 
strSQL = strSQL & " ORDER BY [TransTbl].[LastName]"

or
Code:
strSQL = "SELECT * FROM [TransTbl] WHERE [TransTbl].[Assoc] = '" & InAssoc & "' ORDER BY [TransTbl].[LastName]"

I believe the first method is better as you can then Debug.Print strSQL and check the syntax.

HTH
 
You need to concatenate the strings with the variables. I've not done this over two lines so would do
Code:
strSQL = "SELECT * FROM [TransTbl] WHERE [TransTbl].[Assoc] = '" & InAssoc & "'" 
strSQL = strSQL & " ORDER BY [TransTbl].[LastName]"

or
Code:
strSQL = "SELECT * FROM [TransTbl] WHERE [TransTbl].[Assoc] = '" & InAssoc & "' ORDER BY [TransTbl].[LastName]"

I believe the first method is better as you can then Debug.Print strSQL and check the syntax.

HTH

Gasman it works like charm. Thank you.
 
Multi-Line version:
Code:
strSQL = "SELECT * " & _
	 "FROM [TransTbl] " & _
	 "WHERE [TransTbl].[Assoc] = '" & InAssoc & "' "  & _
	 "ORDER BY [TransTbl].[LastName]"
 
Another way is to use VBA to pass the variable to a querydef as a parameter.
 

Users who are viewing this thread

Back
Top Bottom