Passing value to textbox with sql query via VBA code - MS ACCESS - vba

I am currently working in MS ACCESS. I have 2 forms one called MyForm and the second one name Transit. I have one table called SimulationTable which have 4 fields Fiscal_Year, Scenario_Number, Description and Operating_Unit. I would like with VBA code when clicking in a button to display result of SQL query in the textbox called TXTBOX which is in Transit form. I have tried many times but it doesn't work.
Any idea of how to fix ? Thank you.
Here is the SQL query:
SELECT SimulationTable.Description FROM SimulationTable WHERE Fiscal_Year=Forms!MainForm!OperatingFY AND Operating_Unit = Forms!MainForm!Text3 AND Scenario_Number = Forms!MainForm!Selected_scenario

Could just use DLookup():
Me.TXTBOX = DLookup("[Description]", "SimulationTable", "Fiscal_Year=" & Forms!MainForm!OperatingFY & _
" AND Operating_Unit = " & Forms!MainForm!Text3 & _
" AND Scenario_Number = " & Forms!MainForm!Selected_scenario)
Are these criteria fields all number type? Is TXTBOX bound to a field? If not, could even just put the DLookup() expression in ControlSource property.

It works. I have added apostrophes around the "Operating_Unit" which is a field in text format. Thanks very much June7.
Me.TXTBOX = DLookup("[Description]", "SimulationTable", "Fiscal_Year=" & Forms!MainForm!OperatingFY & " AND Operating_Unit ='" & Forms!MainForm!Text3 & "' AND Scenario_Number =" & Forms!MainForm!Selected_scenario)

Related

ACCESS VBA Unmatched Records Query Not Working When Concatenating

I have been trying to run a query from MS ACCESS VBA. My query works well when I don't add concatenated fields. When I use a concatenated field like in the code below, it turns an empty result.
Is there any work around?
lstStudentName.RowSource = "SELECT [sdtName] & ' ' & [sdtFatherName] & ' ' & [sdtLastName] AS sdtFullName, sdtID FROM tbl_sdt_Info " & _
" LEFT join tbl_sdt_Rounds ON tbl_sdt_Info.sdtID = tbl_sdt_Rounds.sdtID " & _
" WHERE IS NULL(tbl_sdt_Rounds.sdtID)"
Issues with your SQL:
Incorrect use of IS NULL - should be either IsNull(tbl_sdt_Rounds.sdtID) or tbl_sdt_Rounds.sdtID IS NULL. The latter is preferable because it is SQL, IsNull() is a VBA function.
Since there are two sdtID fields, query shouldn't work without table prefix to specify field. I am surprised you get anything.
Although possibly not an issue as is, my preference would be to make sdtID the first field and set ColumnWidths as 0";1.0" and first column as BoundColumn. This will allow viewing and typing first letter of name but sdtID will be listbox value.
Never hurts to build and test query object and when it works, replicate SQL statement in VBA.
lstStudentName.RowSource = "SELECT tbl_sdt_Info.sdtID, sdtName & ' ' & sdtFatherName & ' ' & sdtLastName AS sdtFullName FROM tbl_sdt_Info " & _
"LEFT join tbl_sdt_Rounds ON tbl_sdt_Info.sdtID = tbl_sdt_Rounds.sdtID " & _
"WHERE tbl_sdt_Rounds.sdtID IS NULL;"

Retrieve Data from SQL with input from table

I have a table in excel, with range : Sheets("Sheet1").Range("d4:d215"). These data are similar to PS.WELL in the server.
From that table, I want to retrieve data using this code (other SQL requisite has been loaded, this is the main code only):
strquery = "SELECT PS.WELL, PS.TYPE, PS.TOPSND " & _
"FROM ISYS.PS PS " & _
"WHERE PS.WELL = '" & Sheets("Sheet1").Range("D4:D215") "' AND (PS.TYPE = 'O' OR PS.TYPE = 'O_' OR PS.TYPE = 'GOW') " & _
"ORDER BY PS.WELL"
Unfortunately it didn't work. Can anyone help me how to write the code especially in the 'where' section?
You have to iterate through each item in the range and concatenate the results to a string variable so the contents look like this
'val1','val2','val3'
Then you have to adjust your query code to use the IN operator instead of equals operator. Let's say the string is concatenated to a variable called myrange.
"WHERE PS.WELL IN (" & myrange & ") AND ...
I have solved the problem. The key is to make 2 function of SQL:
to read and write each input
to count number of output per input (an input can have 0, 1, or more output).
then, just call using procedure

Button searches subform, then finds record in main form (Access VBA)

I have this ACCESS form that contains a subform:Form & Subform
I'm trying to create a search button (using VBA) to find a student by name (students' names are not in the table behind the main form).
I've done the first step, which is to search the subform for a student's name, but I'm having trouble with my desired second step. I'd like the code to then take the CWID number of the student and find the matching record in the main form. How would I do this? (My current code is below)
I've tried DoCmd FindRecord and GoToRecord, but it is completely stumping me. I'm Google-learning how to do this and think I'm fundamentally misunderstanding something and am thus unable to search for or understand the answer. Any help would be greatly appreciated.
Private Sub btnSearch_Click()
Dim SQL As String
SQL = "SELECT [AWN Banner].CWID, [AWN Banner].FirstName, [AWN Banner].LastName, [AWN Banner].Freshman, [AWN Banner].Instructor, [AWN Banner].Course " _
& "FROM [AWN Banner] " _
& "RIGHT JOIN [AWNEntry] ON [AWN Banner].CWID = [AWNEntry].CWID " _
& "WHERE [LastName] LIKE '" & Me.txtKeywords & "*' " _
& "ORDER BY [AWN Banner].LastName "
Me.subAwnObj.Form.RecordSource = SQL
Me.subAwnObj.Form.Requery
End Sub
When I create my search boxes I put in the underlying form source a WHERE clause WHERE [field] LIKE "*" & [MySearchBox] & "*" I put such a clause in the subform and the main form I create a JOIN to the subform record with the same WHERE clause defined. Then on click I request all recordsources.

MS Access Using ComboBox Value in SQL Field

Trying to set up a query where one of the fields is selected by the value in a combobox. Can't figure out the right syntax. I'm in the SQL view of the query builder, using the following:
SELECT Deviations.Deviation, Deviations.Rev, Deviations.Title, Deviations.Issued, Deviations.ExpiryDate, Deviations.ExpiryHours, Deviations.ExpOther, Deviations.Active, Deviations.[Forms]![DeviationSelectionForm]![cmbAircraft]
FROM Deviations
WHERE Deviations.[Forms]![DeviationSelectionForm]![cmbAircraft]=True
ORDER BY Deviations.Deviation DESC
The combo box selects the tail number of the aircraft which is a checkbox in the table. There are multiple aircraft tail numbers as checkbox fields. So if there were no combobox and I wanted the query to use as example aircraft 416, the query would be:
SELECT Deviations.Deviation, Deviations.Rev, Deviations.Title, Deviations.Issued, Deviations.ExpiryDate, Deviations.ExpiryHours, Deviations.ExpOther, Deviations.Active, Deviations.[416]
FROM Deviations
WHERE Deviations.[416]=True
ORDER BY Deviations.Deviation DESC
When I test this query it works as I need it to.
So the question is how to I create the query with the combobox in a form identifying the field name of a table?
Build the Query SQL viacode in the combobox afterUpdate event.
Dim strSql as String
strSql = "SELECT Deviations.Deviation, Deviations.Rev, Deviations.Title, Deviations.Issued, " _
& "Deviations.ExpiryDate, Deviations.ExpiryHours, Deviations.ExpOther, " _
& "Deviations.Active, Deviations." & Me!cmbAircraft _
& " FROM Deviations " _
& "WHERE Deviations." & Me!cmbAircraft & " =True " _
& "ORDER BY Deviations.Deviation DESC"
CurrentDb.QueryDefs(<yourqueryname>).SQL = strSql
That said, it seems like you have built a spreadsheet instead of a database.
Your tables are not normalized. Aircraft should be records, not columns. I suggest you read up on database design and normalization.

MS Access SQL query within VBA code

I need a second set of eyes on this SQL query embedded in the VBA code. I'm making an MS Access app that returns a dataset based on the to & from date criteria set by the user in the specific date picker boxes. The sql query that you see actually has been tested statically within MS Access query design view. I tested it with actual dates where you see the Me.from_filter and Me.to_filter. It worked perfectly! If you chose something like from 1/1/2015 to 5/1/2015 it returns columns of all the months you need. Perfect. Now when I embed it in the VBA code and assign it to a control variable, I get the "Run-time error '2342': A RunSQL action requires an argument consisting of an SQL statement." Can someone please eyeball this and tell me what might be wrong?
Option Compare Database
Option Explicit
Dim strSQL As String
Private Sub Command0_Click()
If IsNull(Me.from_filter) Or IsNull(Me.to_filter) Then
MsgBox "You have not entered a start date or end date"
Else
strSQL = "TRANSFORM Sum(dbo_ASSET_HISTORY.MARKET_VALUE) AS SumOfMARKET_VALUE " _
& "SELECT [dbo_FIRM]![NAME] AS [FIRM NAME], dbo_FUND.CUSIP, dbo_FUND.FUND_NAME, dbo_FUND.PRODUCT_NAME " _
& "FROM (dbo_ASSET_HISTORY INNER JOIN dbo_FIRM ON dbo_ASSET_HISTORY.FIRM_ID = dbo_FIRM.FIRM_ID) INNER JOIN dbo_FUND ON dbo_ASSET_HISTORY.FUND = dbo_FUND.FUND " _
& "WHERE (((dbo_FIRM.Name) Like 'Voya F*') And ((dbo_ASSET_HISTORY.PROCESS_DATE) >= #" & Me.from_filter & "# And (dbo_ASSET_HISTORY.PROCESS_DATE) <= #" & Me.to_filter & "#)) " _
& "GROUP BY [dbo_FIRM]![NAME], dbo_FUND.CUSIP, dbo_FUND.FUND_NAME, dbo_FUND.PRODUCT_NAME " _
& "PIVOT [dbo_ASSET_HISTORY]![ASSET_YEAR] & '-' & [dbo_ASSET_HISTORY]![ASSET_MONTH];"
DoCmd.RunSQL (strSQL)
End If
End Sub
RunSQL is for running action queries like update, insert, select into, delete, etc as per Microsoft definition https://msdn.microsoft.com/en-us/library/office/ff194626.aspx , you should probably use OpenQuery or similar to run your query.