VBA - SQL - As String Questions

mickmullen

Registered User.
Local time
Today, 10:29
Joined
Oct 30, 2018
Messages
19
Couple questions.



When a Dim is defined as String (Dim strCriteria As String)


and then I want to use the String in a SQL statement


What does the Quotation and ampersand mean here:


" & strCriteria & "


Context: WHERE ((" & strCriteria & ") AND(" & strCriteria2 & ")
 
You are concatenating literal text (whatever is between the quotes) with whatever is contained by the variable.
 
Variable1 = "This is in the first variable"

Variable2 = "this is in the second variable"

Variable3 = Variable1 & ", " & Variable2 & " and together, along with this text, they create the value inside the third variable"
 
When building an SQL string, form controls must be concatenated as strings but functions do not. Why?

In the examples below, textbox contains text and MyFunction returns a string.

Example with form control:
Code:
db.Execute "UPDATE table SET field = 'some text" & Forms!MyForm!textbox & "';", dbFailOnError

Example with function:
Code:
db.Execute "UPDATE table SET field = 'some text' & MyFunction();", dbFailOnError
 
Because the SQL engine will process the SQL statement and "find" the function and evaluate. Just as if you had referenced the function in a query object. Semi-colon is actually not necessary but doesn't hurt.

Also, DoCmd.RunSQL will allow form control reference to be embedded and evaluated. CurrentDb.Execute doesn't. Function call works in both.
 
Last edited:
If you are interested in the above SQL <=> VBA converter, please note that the versions in that thread date back to 2018.
The latest version is available as a free add-in from:

 

Users who are viewing this thread

Back
Top Bottom