Selecting results from table based on combo box data - sql

Firstly I apologise for my lack of knowledge on SQL.
I currently have two Comboboxes on a form and a list box which looks like the attached image
TroubleshootPage
The first combobox references a table with the list of manufacturers and then the second "Model" combobox updates with model numbers which match the first combobox' data
The List box below needs to display data from the "Solutions" Table. ONLY THE "SolutionText" COLUMN
The Manufacturer selected in "cboManfact" has to match the "ManufacturerSolution" in table "Solutions" and then return "SolutionText" if they match. Same for "cboModel" and "ModelSolution".
I dont want the listbox to display any manufacturer or model text, just the "SolutionText" field when a button db_search is pressed.
Thanks to the help of #LiamH, i currently have the following SQL Command on the RowSource of my list box
This can happen either as the user selects options in the comboboxes or when clicking the green search icon
The problem I am having is with the SQL Query. I currently have this below happening when the user clicks the search button
SELECT [SolutionText] FROM [Solutions] WHERE solutions.ManufacturerSolution like forms![Troubleshoot]!cboManfact & "*" AND solutions.ModelSolution like forms![Troubleshoot]!cboModel & "*"
It displays the SolutionText value in the listbox, but on clicking the "db_search" button, the listbox becomes empty
Private Sub dbSearch_Click()
me.listbox.requery
end sub
Very close to getting this one now, any advice

I have assumed you are using MS-Access, correct me if I am wrong. You may want to consider using access-vba tag if this is correct.
There are a few things wrong with your code. Firstly, docmd.RunSQL cannot be used on select queries. This (SELECT) is not an action query and this command is reserved for action queries only. e.g. DELETE, UPDATE, ALTER, SELECT...INTO.
When you use multiple where clauses use the word AND instead of the ampersand. You don't need to concatenate SQL strings together. String values that are in a query and related to form values need encapsulating in single quotes, like so:
"...WHERE NAME='" & Me.name & "'"
You can use debug.print strSQL or msgbox strSQL to see how your SQL query reads for any errors.
So here's what I would do:
Change the rowsource of the listbox to a query:
SELECT [SolutionText] FROM [Solutions] WHERE solutions.ManufacturerSolution like forms![FORM_NAME]!cboManfact.Column(1) & "*" AND solutions.ModelSolution like forms![FORM_NAME]!cboModel.Column(1) & "*"
The like ... & "*" means that if the combobox is empty it will show all.
You will need some VBA on the on_click event, which will be:
Private Sub dbSearch_Click()
me.listbox.requery
end sub
The requery will change the listbox items based on the records selected in the combo boxes.
I don't know what your intention is when using [Solution Text]?
Are you sure you require column(1) and not column(0)?
I am not sure what your intention was with strTableName?

Solved the issue using the following code:
Private Sub dbSearch_Click()
Dim ManfactQuery As String
Dim ModelQuery As String
Dim strSQL As String
ManfactQuery = Me.cboManfact.Column(1)
ModelQuery = Me.cboModel.Column(1)
If Nz(ManfactQuery) = "" Then
strSQL = "SELECT [Solutions].SolutionText FROM [Solutions] WHERE [Solutions].ModelSolution = '" & ModelQuery & "'"
Else
If Nz(ModelQuery) = "" Then
strSQL = "SELECT [Solutions].SolutionText FROM [Solutions] WHERE [Solutions].ManufacturerSolution = '" & ManfactQuery & "'"
Else
strSQL = "SELECT [Solutions].SolutionText FROM [Solutions] WHERE [Solutions].ManufacturerSolution = " & ManfactQuery & " AND [Solutions].ModelSolution = " & ModelQuery & ""
End If
End If
Me.lstSolution.RowSource = strSQL
End Sub

Related

MS Access fast Combo Box with VBA

I have a form which has a ComboBox on it that pulls records via ID and displays Name from a linked table. Standard look for values in the form combo box wizard generated. It works perfectly fine, but it takes 3-4 minutes every time to find a single record.
I've been trying to research this and found something that looks useful, but can't seem to get it right.
The code I have at the moment:
Private Sub Combo81_Change()
Dim strText As String
Dim strSelect As String
strText = Nz(Me.Combo81.Text, "")
If Len(strText) > 2 Then
strSelect = "SELECT Name FROM CTable WHERE Name LIKE '*" & strText & "*'; "
Debug.Print strSelect
Me.Combo81.RowSource = strSelect
Me.Combo81.Dropdown
End If
End Sub
I found this code on two forums, this is supposed to do the following: "the key is to not have a Row Source defined for the Combo Box. The row source will be defined as the user starts typing letters. Once they get to 3 letters then the row source of the combo box will be defined and the combo box will be told to dropdown."
When I get to 3 letters, a dropdown appears, but it's blank, it doesn't display any results.
I would like when the user types, e.g. "Smith" only those people with the name Smith come up.
I'm relatively new to Access and the DB I'm using the FE/BE with linked tables to a shared network folder and FE on users Desktops.
Any advice? Or alternatively a different solution as to how take my combo box faster and still keep values unique?
you can use following codes to search value in a combo-box in ms access as user type,
suppose we have a combo-box name org_id in our form, for search a value in org_id we need three event on org_id combo-box. AfterUpdate, LostFocus and KeyPress events.
codes are:
Dim strFilter As String ' Module scope variable used for filter on our combo (org_id)
Private Sub org_id_AfterUpdate()
strFilter = ""
strSQL = "SELECT org_tbl.org_id, org_tbl.org_name, org_tbl.org_code FROM org_tbl" & _
" ORDER BY org_tbl.org_code"
org_id.RowSource = strSQL
End Sub
Private Sub org_id_LostFocus()
strFilter = ""
strSQL = "SELECT org_tbl.org_id, org_tbl.org_name, org_tbl.org_code FROM org_tbl" & _
" ORDER BY org_tbl.org_code"
org_id.RowSource = strSQL
End Sub
Private Sub org_id_KeyPress(KeyAscii As Integer)
strSQL = "SELECT org_tbl.org_id, org_tbl.org_name, org_tbl.org_code FROM org_tbl ORDER BY org_tbl.org_code"
If KeyAscii <> 8 Then ' pressed key is not backspace key
strFilter = strFilter & Chr(KeyAscii)
End If
If IsNull(strFilter) = True Or strFilter <> "" Then
If KeyAscii = 8 Then ' pressed key is backspace key
strFilter = Left(strFilter, (Len(strFilter) - 1))
End If
End If
strSQL = "SELECT org_tbl.org_id, org_tbl.org_name, org_tbl.org_code FROM org_tbl" & _
" WHERE org_name Like '*" & strFilter & "*' ORDER BY org_tbl.org_code"
org_id.RowSource = strSQL
org_id.Dropdown
End Sub
I hope this (answer) helps you.
edit:
you can download sample file from following link:
Access combo box to search as you type sample file

Continue Loop in TextBox to search multiple value from Database, MS Access

I've changed the textbox "enter key behavior", so that everytime I hit enter, textbox will go to the next line,
Project's Form View
When user Click the Button, subform show result for the first line, but then how to get result in every line user input.
Private Sub CountButton_Click()
Dim SQL As String
SQL = "SELECT database.Tracking, database.Date, DateDiff(""d"",[Date],Date()) As Aeging FROM database;"
Me.Query1_subform.Form.RecordSource = SQL
Me.Query1_subform.Form.Requery
End Sub
Do I need to use Loop or VbCrLf or something else to function the textbox
Split textbox value to an array and loop array to build comma-separated string or:
strIN = Replace(Me.textbox, vbCrLf, "','")
If InStrRev(strIN, "','") > 0 Then strIN = Left(strIN, Len(strIN)-3)
SQL = "SELECT database.Tracking, database.Date, DateDiff('d', [Date], Date()) As Aging " & _
"FROM database " & _
"WHERE Tracking IN('" & strIN & "');"
Using a textbox relies on users to be consistent with input - not starting input with a CR and no other extraneous characters input accidentally or otherwise.
More reliable alternative is a multi-select listbox of Tracking values. Code loops through selected items and builds comma-separated string.

How to query combo box of only current record/row in Access data entry form?

I have created a data entry form in Access that uses combobox for entering farmer name. The combobox is used for ease and to make sure only farmers from the list are entered. For ease combo box is re-queried as you type in.
The combobox works well for the first entry but previous farmers' names are vanished when queried for the next row. I think, Access is requerying all dropdowns rather than the current drop-down/combo-box.
The VBA for the querying drop down is given below:
Public Sub FilterComboAsYouType(combo As ComboBox, defaultSQL As String,
lookupField As String)
Dim strSQL As String
If Len(combo.Text) > 0 Then
strSQL = defaultSQL & " AND " & lookupField & " LIKE '*" & combo.Text &
"*'"
Else
strSQL = defaultSQL 'This is the default row source of combo box
End If
combo.RowSource = strSQL
combo.Dropdown
End Sub
Private Sub Combo137_Change()
FilterComboAsYouType Me.Combo137, "SELECT farmer.name,farmer.ID FROM farms INNER JOIN farmer ON
farms.ID = farmer.farm_id where farms.ID LIKE" & "'" & Form_Name & "*'", "farmer.name"
End Sub
Private Sub Combo137_GotFocus()
If Form_Name <> "" Then
FilterComboAsYouType Me.Combo137, "SELECT farmer.name,farmer.ID FROM farms INNER JOIN farmer ON
farms.ID = farmer.farm_id where farms.ID LIKE" & "'" & Form_Name & "*'", "farmer.name"
Else
FilterComboAsYouType Me.Combo137, "SELECT farmer.name,farmer.ID FROM farms INNER JOIN farmer ON
farms.ID = farmer.farm_id where farms.ID LIKE" & "'" & "NONE" & "*'", "farmer.name"
End If
End Sub
Yes, all records will show the same filtered list because there is only one combobox and property settings are reflected in all instances. Filtering a combobox RowSource based on value in another field/control is known as "cascading" or "dependent". Also, your RowSource has alias - value saved is not value displayed. When the list is filtered the display alias will not be available for records that have saved value which has been filtered out. This is a well-known issue of cascading combobox. Options for dealing with:
for any form style, only filter the list for new record or when primary value is changed, then reset to full list for existing records
for forms in Continuous or Datasheet view, include lookup table in form RecordSource, bind a textbox to descriptive field from lookup table, position textbox on top of combobox, set textbox as Locked Yes and TabStop No

Access Combo - Filter As You Type?

I started a thread here: Access Form Combobox Partial Filter but it was a bit too specific, and now that I moved past that, I am struggling to get the behavior I want.
Here is the layout:
A form with the detail hidden. The header has an unbound combobox for filtering the form. Once there is a filter to apply, that record is set for the filter on the form, and the detail is shown. The users want to be able to type in the combo, for partial matches, instead of only being able to click the drop down and click to choose an option.
This is the rowsource of the combo:
SELECT [vw_Info_Records]![recordName] & " (" & [vw_Info_Records]![recordNo] & ")" AS frecord, vw_Info_Records.INF_RID
FROM vw_Info_Records
WHERE ((([vw_Info_Records]![recordName] & " (" & [vw_Info_Records]![recordNo] & ")") Like "*" & [Forms]![frmrecords]![cboFindrecord] & "*"))
ORDER BY [vw_Info_Records]![recordName] & " (" & [vw_Info_Records]![recordNo] & ")";
It is set to auto-expand Yes. It is not bound to anything, and limit to list is set to yes.
This is the onchange event:
Private Sub cboFindRecord_Change()
Dim MyCriteria As String
If Me.cboFindRecord.SelStart > 0 Then
Me.cboFindRecord.Dropdown
End If
End Sub
This is the after update:
Private Sub cboFindRecord_AfterUpdate()
Dim Criteria As String
Dim myfilter As String
If Me.cboFindRecord.ListIndex = -1 Then
Me.Form.Filter = ""
Me.FilterOn = False
Me.Detail.Visible = False
Else
Criteria = "[INF_RID] = " & Me.cboFindRecord.Column(1)
With Me.Form
.Filter = Criteria
.FilterOn = True
End With
Me.Detail.Visible = True
End If
End Sub
The first character that is typed in, makes the dropdown expand, and filter to any results that contain that character. Any subsequent characters, and the drop down list doesn't update the filter to re-filter based on the added characters. If I add a requery in the change, I get an error about saving the field, before I do a requery. It wants me to set that "filter" value as a value for the combo, which I wouldn't do, because it's really an in string filter. The user still needs to pick a value from whatever is left in the list, before I can filter the form to that record.
Thanks for any advice as to how to fix this!

Sorting a query by Listbox with multiselect?

My task is create a query that is filtered by the results of a listbox with multiselect. I have a table, named contacts, which has a field named 'Sources'. This is the field that is displayed in my listview. I am sorting by the 'Sources' value
From here, I can multiselect the options, and hit a submit button. When I do so, I get a query but it seems to simply display all of the values.
Therefore, my question is, how can I create a query sorted by the Sources tab? I know that I need a onclick function, but I am very unfamiliar with VB. Any help would be appreciated!
You can modify the following to use your control names. You didn't mention where/how your query is created, but you can merge this code with yours...
Private Sub cmdBuildWhere_Click()
Dim varItem As Variant
Dim strWhere As String
If Me.lstHierarchy.ListIndex < 1 And Me.lstHierarchy.ItemsSelected.Count = 0 Then ' No items selected
MsgBox "You did not select any sources. ", vbOKOnly, "Select Sources"
Exit Sub
End If
strWhere = "WHERE "
For Each varItem In Me.lstHierarchy.ItemsSelected
strWhere = strWhere & "[Sources] = '" & Me.lstHierarchy.Column(0, varItem) & "' Or "
Next varItem
' remove final ' or ' and add Sort
strWhere = Trim(left(strWhere, Len(strWhere) - 4)) & " Order By Sources;"
Debug.Print strWhere
End Sub