How do I store the results of my select statement in a variable? - sql

My code so far is this. The last line gives me a compile error: "expected end of statement".
Dim strSql As String
Dim groupId As String
strSql = "Select ID from RevenueGroup where description = '" & ListO.Value & "'"
groupId = CurrentProject.Connection.Execute strSql

You are looking at something kinda like this
Dim strSql As String
Dim groupId As String
strSql = "Select ID from RevenueGroup where description = '" & ListO.Value & "'"
Dim rec As Recordset
set rec= CurrentProject.Connection.Execute strSql
groupId = rec(0)
You need to set the results of the query to a recordset and then pull the first value from its results. Without all the defined variable, I cannot get this to fully compile but this should be a good template to start from.

Related

Access VBA creating a query that uses a variant as a where condition

I am trying to write a vba code that will create a query in Access with a where condition based off of the value of a cell from another table. My issue is that when I am trying to pull a string from the varRecords(0,0) Variant it becomes a parameter for the new query and not a string. I tried using cstr() function but it was still becoming a parameter. If I use msgbox to test what is being created it appears as a string. I may have left some stuff out of the code but the basics are below.
Dim dbsEmails As DAO.Database
Dim rstEmails As DAO.Recordset
Dim varRecords As Variant
Dim RecordCounter As Long
Dim qdfTemp As QueryDef
Dim strSQL As String
Dim strSQL2 As String
Set dbsEmails = CurrentDb
strSQL = "Select Email, ID from tbl_Email"
Set rstEmails = dbsEmails.OpenRecordset(strSQL, dbOpenSnapshot)
rstEmails.MoveLast
RecordCounter = rstEmails.RecordCount
rstEmails.MoveFirst
varRecords = rstEmails.GetRows(RecordCounter)
strSQL2 = "Select ID, Stuff from tbl2 Where id =" & varRecords(0,0)
SetqdfTemp = CurrentDb.CreateQueryDef("Pending Report", strSQL2)
End Function
Try making it a string:
strSQL2 = "Select ID, Stuff from tbl2 Where id = '" & varRecords(0,0) & "'"

Use the Result of a SELECT STATEMENT as a VARIABLE

I have the following code and it works just fine:
Dim result As Integer
result = 20
DoCmd.RunSQL "INSERT INTO ReportingTable (BUDGETPER1) VALUES (" & result & ");"
I don't really want to hardcode the 20 but rather populate using a SELECT statement:
select PD01 from SetVariables WHERE VariableType = 'HEADCOUNT' and BusinessUnit = 511
(the result of this SELECT statement is 20, I have tested it and it is fine)
What would be the easiest way of achieving this? I understand that in this specific example I would be able to achieve the desired result using Dlookup but I need to get my head around the concept of defining a variable with a select statement.
You can use a SELECT query to determine the data to be inserted into your table:
Sub sInsertData()
Dim db As DAO.Database
Dim strSQL As String
Set db = DBEngine(0)(0)
strSQL = "INSERT INTO ReportingTable (BUDGETPER1) " _
& " SELECT PD01 FROM SetVariables " _
& " WHERE VariableType='headcount' AND BusinessUnit=511;"
db.Execute strSQL
Set db = Nothing
End Sub
You could also then replace "headcount" and "511" with other values as required.
Regards,

Access VBA: Cannot combine variable and string in SQL query

I have a list of users (as string variable) and want to use it as the criteria (one user at a time) for my SQL to pick the first item's code. So I put a SQL query as a string to run it later in the code.
I've tried this:
strSQL = "SELECT TOP 1 Item.Code FROM Item WHERE Item.User = '"
strSQL = strSQL & strUserName & "' ORDER BY ID DESC"
If the strUserName = "A-user" for example, I only get this SQL string, according to "Quick Watch...":
SELECT TOP 1 Item.Code FROM Item WHERE Item.User = 'A-user
The part with "' ORDER BY ID DESC" isn't included in the SQL string at all!
And for running the SQL query by using "Set rst = CurrentDb.OpenRecordset(strSQL)", I get this error:
Run-time error '3075':
Syntax error (missing operator) in query expression 'Item.User = "A-user"
How can I fix that?
I don't see how your code triggers that 3075 error. However I would use a parameter query instead. That way you can avoid problems with quoted values in your SQL statement.
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSelect As String
Dim strUserName As String
strUserName = "A-user"
strSelect = "SELECT TOP 1 i.Code FROM [Item] AS i WHERE i.User = [which_user] ORDER BY i.ID DESC"
Set qdf = CurrentDb.CreateQueryDef(vbNullString, strSelect)
qdf.Parameters("which_user").Value = strUserName
Set rs = qdf.OpenRecordset
Access sometimes complains about the use of single-quotes. And also add a semi-colon to the end of the statement. Try changing the code to this (where double-quotes are escaped with an extra double-quote:
strSQL = "SELECT TOP 1 Item.Code FROM Item WHERE Item.User = "
strSQL = strSQL & """" & strUserName & """" & " ORDER BY ID DESC;"

Very simple module failing. Error: 91, Object variable or With block variable not set

This code simply pulls information from a table, and inserts it into a temporary table. From there, it updates the rows with the correct program name that correlates to the program id given, which is where it fails.
I'm not sure why this simple module won't run, I've declared the variable, as well as initialized it. The query is super simple, as well. Any help would be appreciated -- I have got to me missing something painfully obvious.
Dim year As String
Dim month As String
Dim contract As String
Dim programId As String
Dim ConsumerId As String
Dim programName As String
Dim db As Database
Dim Records As DAO.recordset
Dim Records2 As DAO.recordset
year = Forms!formAllentownMasterGeneration!cboYear
month = Forms!formAllentownMasterGeneration!cboMonth
contract = Forms!formAllentownMasterGeneration!cboContract
'Empty temporary table
strSQL = "DELETE * FROM billing_days_allentown1_temp"
DoCmd.RunSQL (strSQL)
'Gather and insert consumer information into temp table
strSQL = "INSERT INTO Billing_days_allentown1_temp (consumer_id, program_id, lname, fname, dob, transport_type, memo) SELECT consumer_info.consumer_id, consumer_info.program_id, consumer_info.lname, consumer_info.fname, consumer_info.dob, consumer_info.transport_type, consumer_info.memo FROM consumer_info WHERE contract_name = [contract]"
DoCmd.RunSQL (strSQL)
'Get ID's of all consumers in temp table so we can find program names
strSQL = "SELECT consumer_id, program_id FROM Billing_days_allentown1_temp"
Set Records = db.OpenRecordset("SELECT consumer_id, program_id FROM billing_days_allentown1_temp")
While Not Records.EOF
ConsumerId = Records!Fields(0)
programId = Records!Fields(1)
strSQL2 = "SELECT name FROM program_info where program_id = [programId]"
Set Records2 = db.OpenRecordset("SELECT name FROM program_info where program_id = [programId]")
programName = Records2!Fields(0)
strSQL2 = "UPDATE billing_days_allentown1_temp SET program_name = [ProgramName] WHERE program_id = programId and consumer_id = [consumerId]"
DoCmd.RunSQL (strSQL2)
Records.MoveNext
Wend
DoCmd.Close acForm, "formAllentownMasterGeneration"
Additionally (but admittedly a problem I haven't looked into yet), it prompts me for the contract name, despite providing it in the form. I'm sure I am referencing the variable wrong in a query; but my VBA is pretty rusty. If it's a quick fix, I'd appreciate someone pointing that out as well, otherwise it's something I'll fix on my own in due time.
Thank you.
Try this...it should clean up your SQL statements a little...and pass the variables, not [variable]
Dim year As String
Dim month As String
Dim contract As String
Dim programId As String
Dim ConsumerId As String
Dim programName As String
Dim strSQL As String
Dim strSQL2 As String
Dim db As Database
Dim Records As DAO.recordset
Dim Records2 As DAO.recordset
year = Me.cboYear '<--- Assuming you are on Forms!formAllentownMasterGeneration - you can use Me.
month = Me.cboMonth
contract = Me.cboContract
'Empty temporary table
strSQL = "DELETE * FROM billing_days_allentown1_temp"
DoCmd.RunSQL (strSQL)
'Gather and insert consumer information into temp table
strSQL = "INSERT INTO Billing_days_allentown1_temp (consumer_id, program_id, lname, fname, dob, transport_type, memo) " & _
"SELECT consumer_info.consumer_id, consumer_info.program_id, consumer_info.lname, consumer_info.fname, consumer_info.dob, consumer_info.transport_type, consumer_info.memo " & _
"FROM consumer_info " & _
"WHERE contract_name =" & contract
DoCmd.RunSQL (strSQL)
'Get ID's of all consumers in temp table so we can find program names
strSQL = "SELECT consumer_id, program_id " & _
"FROM Billing_days_allentown1_temp"
Set Records = db.OpenRecordset(strSQL)
While Not Records.EOF
ConsumerId = Records!Fields(0)
programId = Records!Fields(1)
strSQL2 = "SELECT name " & _
"FROM program_info " & _
"WHERE program_id = " & programId
Set Records2 = db.OpenRecordset(strSQL2)
ProgramName = Records2!Fields(0)
strSQL2 = "UPDATE billing_days_allentown1_temp " & _
"SET program_name = " & ProgramName & " " & _
"WHERE program_id = " & programId & " and consumer_id = " & consumerId
DoCmd.RunSQL (strSQL2)
Records.MoveNext
Wend
DoCmd.Close acForm, "formAllentownMasterGeneration"

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")