Using a VBA variable in SELECT Sql statement - sql

Is their a way to use a declared VBA variable in a SELECT Sql statement as follows (I have a table called myTable and i want to set the referenced field by passing the declared string myVar) :
e.g passVar("English")
NB: Am using Microsoft Access
Private Function passVar(myVar as string)
Dim db As Database
Dim qdf As DAO.QueryDef
Dim stmnt As String
Set db = CurrentDb()
Set qdf = db.QueryDefs("SelectSubjectQuery")
stmnt = "SELECT [myTable].[myVar] = " &Chr$(34) & myVar & Chr$(34) & _
//other SQL statements go here
qdf.SQL = stmnt
End Function
Each time i run the query a dialog box appears asking for the value of mytable.myvar instead of passing myvar i.e Eglish as the referenced field on myTable.

Yes, build the SQL statement as a string like this:
stmnt = "SELECT " & [myTable] & "." & [myVar] & " = " &Chr$(34) & myVar & Chr$(34) & _
VBA should then fill in the names for MyTable and MyVar when the code is run and the string is built.

stmnt = "SELECT [myTable]." & myVar & _
Got it to working by writing as above (no need for the equals sign as the string is passed through the function). Thanks for the insight #rcfmonarch

Related

SQL on VBA: Compilation error, a function or variable was expected

I have the code below but it isnt working. It gives me the error: Compilation error, a function or variable was expected.
I guess the error is on the Database.Execute method, but I didnt come with a solution yet.
Sub ChavesMontante()
Dim dbschaves As Database
Dim rschaves As DAO.Recordset
Dim tipodechave As String
Dim SQLCMD As String
Dim chave As String
Set dbschaves = CurrentDb
chave = "BED20777"
SQLCMD =
"(SELECT us.instalacao, ch.bloco, us.tipounidade " & _
"FROM (SELECT useccionadora, bloco " & _
"FROM sgdprd.redeprimaria rp " & _
"WHERE rp.useccionadora IS NOT NULL " & _
"CONNECT BY rp.nox = PRIOR rp.fontex AND rp.noy = PRIOR rp.fontey " & _
"START WITH rp.useccionadora = '" & chave & "' ) ch " & _
"INNER JOIN sgdprd.useccionadora us ON ch.useccionadora= us.instalacao) "
Debug.Print SQLCMD
Set rschaves = dbschaves.Execute(SQLCMD)
End Sub
Execute is used for action SQL statements (UPDATE, DELETE, INSERT), not to set a Recordset object.
Try the following changes:
Dim dbschaves As DAO.Database
...
Set rschaves = dbschaves.OpenRecordset(SQLCMD)
Also, remove the outer parens enclosing the entire SQL statement. I have never seen CONNECT BY PRIOR START WITH. Does the query open in Access?

Run Time error 3061 Too Few parameters. Expected 6. Unable to update table from listbox

All,
I am running the below SQL and I keep getting error 3061. Thank you all for the wonderful help! I've been trying to teach myself and I am 10 days in and oh my I am in for a treat!
Private Sub b_Update_Click()
Dim db As DAO.Database
Set db = CurrentDb
strSQL = "UPDATE Main" _
& " SET t_Name = Me.txt_Name, t_Date = Me.txt_Date, t_ContactID = Me.txt_Contact, t_Score = Me.txt_Score, t_Comments = Me.txt_Comments" _
& " WHERE RecordID = Me.lbl_RecordID.Caption"
CurrentDb.Execute strSQL
I am not sure but, you can try somethink like that
if you knom the new value to insert in the database try with a syntax like this one
UPDATE table
SET Users.name = 'NewName',
Users.address = 'MyNewAdresse'
WHERE Users.id_User = 10;
Now, if you want to use a form (php)
You have to use this
if(isset($_REQUEST["id_user" ])) {$id_user = $_REQUEST["id_user" ];}
else {$id_user = "" ;}
if(isset($_REQUEST["name" ])) {$name= $_REQUEST["name" ];}
else {$name = "" ;}
if(isset($_REQUEST["address" ])) {$address= $_REQUEST["adress" ];}
else {$adress= "" ;}
if you use mysql
UPDATE table
SET Users.name = '$name',
Users.address = '$adress'
WHERE Users.id_User = 10;
i don't know VBA but I will try to help you
Going on from my comment, you first need to declare strSQL as a string variable.
Where your error expects 6 values and access doesn't know what they are. This is because form objects need to be outside the quotations of the SQL query, otherwise (as in this case) it will think they are variables and obviously undefined. The 6 expected are the 5 form fields plus 'strSQL'.
Private Sub b_Update_Click()
Dim db As DAO.Database
dim strSQL as string
Set db = CurrentDb
strSQL = "UPDATE Main" & _
" SET t_Name = '" & Me.txt_Name & "'," & _
" t_Date =#" & Me.txt_Date & "#," & _
" t_ContactID =" & Me.txt_Contact & "," & _
" t_Score =" & Me.txt_Score & "," & _
" t_Comments = '" & Me.txt_Comments & "'," & _
" WHERE RecordID = '" & Me.lbl_RecordID.Caption & "';"
CurrentDb.Execute strSQL
end sub
Note how I have used double quotes to put the form fields outside of the query string so access knows they aren't variables.
If your field is a string, it needs encapsulating in single quotes like so 'string'. If you have a date field it needs encapsulating in number signs like so #date# and numbers/integers don't need encapsulating.
Look at the code I have done and you can see I have used these single quotes and number signs to encapsulate certain fields. I guessed based on the names of the fields like ID's as numbers. I may have got some wrong so alter where applicable... Or comment and I will correct my answer.

Error using CurrentDb.Execute(sqlStr) despite SQL string functioning properly in query builder

I am building a MS Access database and I cannot find a solution to my issue anywhere. All I want to do is trigger an update to my table using SQL code upon clicking a button, however, each time I try to run this code I get the error: "Run time error 3061, Too few parameters. Expected 1". The naming of all the tables and fields I call in my SQL code is correct. I copy/pasted the SQL string from my debug print into a query builder and it worked without issue. My code is:
Private Sub cmdAddRev_Click()
Dim compNum As String
Dim docPath As String
Dim filePath As String
Dim lastRev As Integer
Dim updateRev As Integer
Dim sqlStr As String
compNum = Me.cboRevSelection.Value
docPath = Me.tboRevDocLoc.Value
filePath = Me.tboRevFileLoc.Value
lastRev = DLookup("numLastRev", "tblComponents", "num = [Forms]![frmRevisor]![cboRevSelection]")
updateRev = lastRev + 1
sqlStr = " UPDATE tblComponents "
sqlStr = sqlStr & " SET numLastRev = " & updateRev
sqlStr = sqlStr & " WHERE num = [Forms]![frmRevisor]![cboRevSelection] "
CurrentDb.Execute (sqlStr) 'this line is flagged when the error happens
Debug.Print sqlStr
End Sub
Change this line:
sqlStr = sqlStr & " WHERE num = [Forms]![frmRevisor]![cboRevSelection] "
to this:
sqlStr = sqlStr & " WHERE num = '" & [Forms]![frmRevisor]![cboRevSelection] & "'"
SQL from VBA, doesn't like parameters. Always use your references outside of the quotes, so that the query going to the execute already has values in it. (although using a parametized query would be better still...)
You can't reference a form when executing SQL via VBA. There are several options. Set a tempvar to the desired value and reference the tempvar in the SQL or create a public function referencing the form and use the function in the SQL
Public Function RevSelection()
RevSelection = [Forms]![frmRevisor]![cboRevSelection]
End Function
Then use
sqlStr = sqlStr & " WHERE num = RevSelection()"
or, the simplest, reference it as a value.
sqlStr = sqlStr & " WHERE num =" & [Forms]![frmRevisor]![cboRevSelection]

Store a sql select statement, ran from VBA, in a numeric variable

I'm working on creating a dynamic pass-through query and in order to do so I first need to query my local db and get an ID.
This ID is what I will put into my pass-through query for my WHERE clause of the query.
My string:
getCorpID = "SELECT corpID " & _
"FROM dbo_corp " & _
"WHERE name = " & Forms.frmMain.Combo4.Value
I'm then trying to do something akin to:
CorpID (integer) = docmd.runsql (getCorpID)
I realize, however that docmd runsql doesn't work with select statements, or return a value even. What can I use to run my string
getCorpId
as sql and store the result (It will only be one result, every time.. one number) in my variable CorpID
Thank you.
Consider about using Recordset :
Dim dbs As DAO.Database
Dim rsSQL As DAO.Recordset
Dim getCorpID As String
Dim CorpID
Set dbs = CurrentDb
getCorpID = "SELECT corpID " & _
"FROM dbo_corp " & _
"WHERE name = " & Forms.frmMain.Combo4.Value
Set rsSQL = dbs.OpenRecordset(getCorpID , dbOpenSnapshot)
rsSQL.MoveFirst
CorpID = rsSQL.Fields("corpID")

SQL Error Access 2010 VBA Update Command

I need help figuring out an error in my SQL statement. I have been trying several things, but nothing seems to work?
This is the error message I receive
Run-time error '3075':
Syntax error (missing operator) in query expression '([description] = Manufacturing and Delivery Schedule AND [pr_num] = 83)'.
This is my code:
Private Sub Command6_Click()
' ===================================================
' Receives the selected item in the combo box
' ===================================================
' Open the Database connection
Dim data_base As Database
Set data_base = CurrentDb
' Grab description and pr number from the form
Dim desc As string
dim pr_number as long
desc = Combo4.Value
pr_number = Text8.Value
' Build the query
Dim query As String
query = "UPDATE VDR_Table " & _
"SET [received] = [p1] " & _
"WHERE ([description] = " & desc & _
" AND [pr_num] = " & pr_number & ");"
Dim rec_set As DAO.Recordset
Set rec_set = data_base.OpenRecordset(query)
' Build the QueryDef
Set qd = data_base.CreateQueryDef("")
qd.SQL = query
' Execute query
qd.Parameters("p1").Value = true
qd.Execute
' Close nad null record set
rec_set.close
set rec_set = nothing
' Close the connection to the database
data_base.Close
' Prompt the user success
MsgBox "Item has been received"
End Sub
Thanks in advance for any help!
You need to enclose the description field value you are setting in quotes since it is a string field. It should look like this:
' Build the query
Dim query As String
query = "UPDATE VDR_Table " & _
"SET [received] = [p1] " & _
"WHERE ([description] = '" & desc & _
"' AND [pr_num] = " & pr_number & ");"
Removed the links below since they don't matter in this case.
Also, I would recommend using parameters instead of string concatenations to avoid SQL injections. Here's an example of using parameters with VBA - http://support.microsoft.com/kb/181734 - and here is some reasoning on why to use parameterized sql - http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html.