Use the Result of a SELECT STATEMENT as a VARIABLE - vba

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,

Related

Access VBA RunSQL Error

I'm trying to insert into a table the top x records from a query data-set. However I keep getting the run-time error '3061' Too few parameters. Expected 1. I've tried a few things but it doesn't make any difference.
Private Sub UpdateGA_Click()
Dim dbs As DAO.Database
Dim strSQL As String
Dim rounds As Integer
Dim playerid As Long
Set dbs = CurrentDb
rounds = Me.NoOfScores.Value
playerid = Me.lngPlayerID.Value
strSQL = "INSERT INTO [tbl_TopRounds] ( [lngPlayerID], [lngRoundID], [dblPlayedTo], [dteRoundDate]) " & _
" SELECT TOP " & Me.NoOfScores.Value & " [lngPlayerID], [lngRoundID], [dblPlayedTo], [dteRoundDate] FROM qry_LastRounds" & _
" WHERE [lngPlayerID] = " & Me.lngPlayerID.Value & _
" ORDER BY [dblPlayedTo], [dteRoundDate] DESC;"
dbs.Execute strSQL
End Sub
I'm expecting that x (based on a form parameter) records will be written to the tbl_TopRounds.
VB Error on executing
Any help would be appreciated.
Normally this error means that you made a mistake in field name. Set breakpoint on last command, run the sub, open immediate window and type ?strSQL. Copy received SQL text and try to run it in query builder, it will show column name which doesn't exist in the table. The error may be in the query qry_LastRounds, check it first by opening

How to pass a SQL query result to variable with VBA Access

I need to create a standalone function which checks whether a value is true or false. I have attempted to set up a SQL query that does this, but can't get the result to pass to the variable.
The query will always return only one record.
How can I pass the result of the SQL string as the returning value of the function?
UPDATED
Private Function HasBM(iMandate As Variant) As Boolean
'Returns boolean value for whether or not mandate has a benchmark
Dim sSQL1 As String
Dim sSQL2 As String
Dim db As Database
Dim rs As Recordset
sSQL1 = "SELECT tbl_Mandate_Type.BM_Included " & _
"FROM tbl_Mandate_Type INNER JOIN tbl_MoPo_BM ON tbl_Mandate_Type.Mandate_Type_ID = tbl_MoPo_BM.MandateType_ID " & _
"WHERE (((tbl_MoPo_BM.MoPo_BM_ID)="
sSQL2 = "));"
Set db = CurrentDb
Set rs = db.Execute(sSQL1 & iMandate & sSQL2)
HasBM = rs.Fields(0).Value
End Function
UPDATE 2: SOLUTION
Thanks for Magisch and HansUp I ended up getting two solutions that work:
DLOOKUP Solution by Magisch as I implemented it:
Private Function HasBM2(iMandate As Variant)
'Returns boolean value for whether or not mandate has a benchmark
Dim tmp As String
tmp = CStr(DLookup("tbl_MoPo_BM.MandateType_ID", "tbl_MoPo_BM", "tbl_MoPo_BM.MoPo_BM_ID = " & iMandate))
HasBM2 = DLookup("tbl_Mandate_Type.BM_Included", "tbl_Mandate_Type", "Mandate_Type_ID =" & tmp)
End Function
Second Solution using recordset as HansUp helped create:
Private Function HasBM(iMandate As Variant) As Boolean
'Returns boolean value for whether or not mandate has a benchmark
Dim sSQL1 As String
Dim sSQL2 As String
Dim db As Database
Dim rs As dao.Recordset
sSQL1 = "SELECT tbl_Mandate_Type.BM_Included " & _
"FROM tbl_Mandate_Type INNER JOIN tbl_MoPo_BM ON tbl_Mandate_Type.Mandate_Type_ID = tbl_MoPo_BM.MandateType_ID " & _
"WHERE (((tbl_MoPo_BM.MoPo_BM_ID)="
sSQL2 = "));"
Set db = CurrentDb
Set rs = db.OpenRecordset(sSQL1 & iMandate & sSQL2)
HasBM = rs.Fields(0).Value
rs.close
End Function
You can use the DLookup function native to access for this. Since you have an INNER JOIN in your SQL, you will have to use it twice, but it'll still work.
Use a temporary string variable to store the temporary output, like this:
Dim tmp as String
tmp = Cstr(DLookup("tbl_MoPo_BM.MandateType_ID","tbl_MoPo_BM","tbl_MoPo_BM.MoPo_BM_ID = " & iMandate)) 'This is to fetch the ID you performed the inner join on
HasBM = DLookup("tbl_Mandate_Type.BM_Included","tbl_Mandate_Type","Mandate_Type_ID =" & tmp) ' this is to get your value
Using your DoCmd.RunSQL will not suffice since its for action queries only (INSERT, DELETE, UPDATE) and incapable of returning the result.
Alternatively, you can use a Recordset with your SQL query to fetch what you want, but thats more work and the DLookup is designed to exactly avoid doing that for single column return selects.

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

Use a ComboBox Value as part of an SQL Query? (MS Access 2010-2013)

I have a Database that we use to create Bills of Materials from Tags in AutoCAD. Because of the nature of this, I need to create 3 separate queries. One for our "Steel", one for our
"Non-Steel", and one for our "Uncut Tubes".
The SQL for the Queries is as follows:
Steel:
SELECT DISTINCTROW Sum([CUT-LENGTH-WEIGHT]) AS [SumOfCUT-LENGTH-WEIGHT], Sum([CUT-SHEET-WEIGHT]) AS [SumOfCUT-SHEET-WEIGHT], Sum([TOTAL-SHEETING-WEIGHT]) AS [SumOfTOTAL-SHEETING-WEIGHT], Sum([TOTAL-ITEM-WEIGHT]) AS [SumOfTOTAL-ITEM-WEIGHT]
FROM [13-1302 Cut-Lengths];
Non-Steel:
SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=23));
Uncut Tubes:
SELECT DISTINCT [13-1302 Cut-Lengths].[TOTAL-LENGTH-WEIGHT], [13-1302 Cut-Lengths].MATERIAL, [13-1302 Cut-Lengths].ORDER
FROM [13-1302 Cut-Lengths]
ORDER BY [13-1302 Cut-Lengths].ORDER;
I have a ComboBox that chooses the Job Number (For Main and Uncut Tubes, e.g. 13-1302) and a Textbox that displays the JobID (For Non-Steel).
Is there a way that I can set up the SQL shown above to look at the ComboBox and TextBox Values, instead of me having to change them by hand?
EDIT
I figured it all out now. (Thank you Elias)
Basically, I cannot use a Field on a table as a RecordSource in SQL, in other words, Combo26 cannot be the Table in an SQL Query. HOWEVER, what CAN be done is to use VBA to inject that value into an SQL Definition, then use that definition as a Recordsource.
I will place the code for my Button below so anyone can use it and reference it:
Private Sub Command27_Click()
Dim dbs As Database
Dim rstSQL As DAO.Recordset
Dim strSQL As String
Dim strSQL2 As String
Dim strSQL3 As String
Dim Field As String
Set dbs = CurrentDb
Field = [Forms]![frmBOM_Combined]![Text26].[Value]
strSQL = "SELECT DISTINCTROW Sum([CUT-LENGTH-WEIGHT]) AS [SumOfCUT-LENGTH-WEIGHT], Sum([TOTAL-SHEETING-WEIGHT]) AS [SumOfTOTAL-SHEETING-WEIGHT], Sum([TOTAL-ITEM-WEIGHT]) AS [SumOfTOTAL-ITEM-WEIGHT] FROM " & "[" & [Forms]![frmBOM_Combined]![Text26].[Value] & "]" & ";"
strSQL2 = "SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight FROM tbl2013BOM GROUP BY tbl2013BOM.fJobID HAVING (((tbl2013BOM.fJobID)= " & [Forms]![frmBOM_Combined]![Combo25].[Value] & "));"
strSQL3 = "SELECT DISTINCT [TOTAL-LENGTH-WEIGHT], [MATERIAL], [ORDER] FROM " & "[" & [Forms]![frmBOM_Combined]![Text26].[Value] & "]" & " ORDER BY [ORDER];"
Debug.Print strSQL
Debug.Print strSQL2
Debug.Print strSQL3
DoCmd.OpenForm ("frmEstWeight")
Forms!frmEstWeight.RecordSource = strSQL
Forms!frmEstWeight.frmTestBomWeight.Form.RecordSource = strSQL2
Forms!frmEstWeight.frmTotalLengthWeight.Form.RecordSource = strSQL3
End Sub
This is working exactly as it should with no errors or anything.
This is within a form correct?
If so, replace the manual values you put in with
REST OF THE QUERY HERE " & Me!Controlname.value & " REST OF THE QUERY HERE
and if you are using something with a control source then just reset the control source value.
me!ControlWithResult.control source = "SELECT tbl2013BOM.fJobID, Sum (tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=" & me!controlname.value & "));"
For Non-Steel try:
On the VBA for the popup form
me!Combo25.rowsource = "SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=" & forms!MAINFORMNAME! &"));

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

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.