MS Access fast Combo Box with VBA - sql

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

Related

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

MS Access - Text field retuns the querys string instead of the query result value

I have tried a few variations, and all seem to give me the same result - so I am overlooking something pretty simple I think.
I have a text box for an account number, a search button, and a text box for the result of the search query. However, when I hit search - the query itself gets added to the second text box instead of the expected result of 1 or 0.
This is my latest attempt, found on this site:
Private Sub SearchAcctNumber_Click()
Dim strsearch As String
Dim Task As String
If IsNull(Me.Text0) Or Me.Text0 = "" Then
MsgBox "Please type in your account number.", vbOKOnly, "Acct Num Needed"
Me.Text0.SetFocus
Else
strsearch = Me.Text0.Value
Task = "SELECT I_Ind FROM dbo_BC WHERE (([ACCOUNT_NUMBER] Like ""*" & Text0 & "*""))"
Me.Text2 = Task
End If
End Sub
Is anyone able to help me see the error I am making? It is driving me nuts that something so simple isn't working how I thought it should.
Edit: Wanted to add that I've also tried DLookup and get the same result in other iterations of attempts at this.
You may want to reconsider the Like approach in this case. Anyways, the issue is that you assign a string (the SQL command) to the textbox and this is what you see.
Try this instead:
Private Sub SearchAcctNumber_Click()
If IsNull(Text0.Value) Then
MsgBox "Please type in your account number.", vbOKOnly, "Acct Num Needed"
Text0.SetFocus
Exit Sub
End If
Dim strSearch As String
Dim strCriteria As String
strSearch = Text0.Value
strCriteria = "ACCOUNT_NUMBER Like '*" & strSearch & "*'"
Text2.Value = Nz(DLookup("I_Ind", "dbo_BC", strCriteria), "Not found...")
End Sub
You could also "search" while you type on Text0. Set the minimum number of characters before attempting to locate it.
Private Sub Text0_Change()
If Len(Text0.Text) > 3 Then
Text2.Value = Nz(DLookup("I_Ind", "dbo_BC", "ACCOUNT_NUMBER Like '*" & Text0.Text & "*'"), vbNullString)
End If
End Sub
One possible way is, that you change Text2 type to combo box. Then you set Text2.recordsource = Task and you refresh the displayed value with Me.Text2.requery.
Another way is to open a recordset, read the value, and set Text2 value.
Dim r as dao.recordset, db as dao.database
set db = currentdb()
set r=db.openrecordset(Task)
Me.Text2 = r(0).value
Set r = Nothing

Selecting results from table based on combo box data

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

MS access sum results between two dates as text box in form

I issue following query in SQL and works fine
SELECT SUM(goudOpkoop.winst)
FROM goudOpkoop
WHERE goudOpkoop.date
BETWEEN '2015-1-10' AND '2015-1-22'
I would like to have the results in a Form in Textbox 3 (name Text183) when last of two dates, one in Textbox 1 (name Text179) and other in textbox 2 (name Text181) have been picked.
I think I would need to use AfterUpdate code builder for Textbox 2 and issue there the query to eventually show results in Textbox 3.
I have already linked with SQL server.
Information: ODBC;DSN=Essence Test;;TABLE=goudOpkoop
In me not being a professional in VBA I have no clue how to get this working.
Not tested, but should do the trick slightly, unless I made a typo.
Change the format of your 2 dates textboxes in "Short Date", that way you will have a calendar picker and you will ensure that your date have a correct format
Create this sub in your form module :
Private Sub CheckSUM()
Dim RST As Recordset
Dim SQL As String
' Reset the result textbox
Text183.value = ""
' If your 2 date textboxes are not populated, cancel
If Text179.Value = "" or Text181.Value = "" Then Exit Sub
' Prepare the query, with proper formating of the dates
SQL = " SELECT SUM(goudOpkoop.winst) AS mySum " & _
" FROM goudOpkoop " & _
" WHERE goudOpkoop.Date " & _
" BETWEEN '" & Format(Text179.Value, "YYYY-MM-DD") & "' " & _
" AND '" & Format(text181.Value, "YYYY-MM-DD") & "'"
' Execute the query
Set RST = CurrentDb.OpenRecordset(SQL)
' If the query is valid and returned something, we recuperate the value
If Not RST.BOF Then
Text183.Value = RST!mySum
End If
' Cleaning
RST.Close
Set RST = Nothing
End Sub
Then, for your 2 dates textboxes, create an afterupdate event and call the previous sub in them:
Private Sub Text179_AfterUpdate()
CheckSUM
End Sub
Private Sub Text181_AfterUpdate()
CheckSUM
End Sub

Excel combo box problem

I have a form in Excel with a combo box control. I want the values to be filled from a database table when the combo box is opened using what has already been typed in as a LIKE criteria. This is the code I have so far for the DropButtonClick event to achieve this.
Private Sub cboVariety_DropButtonClick()
Static search_text As String
Static is_open As Boolean
Dim rs As New Recordset
If is_open Then
is_open = False
Exit Sub
End If
is_open = True
If search_text = cboVariety Then Exit Sub
search_text = cboVariety
cboVariety.Clear
cboVariety.AddItem search_text
If Len(search_text) > 2 Then
rs.Open _
"SELECT Name FROM tbl_Varieties " & _
"WHERE Name LIKE '%" & search_text & "%' " & _
"ORDER BY Name", connect_string, adOpenStatic
Do Until rs.EOF
If rs!Name <> search_text Then cboVariety.AddItem rs!Name
rs.MoveNext
Loop
rs.Close
End If
End Sub
The problem is that the DropButtonClick event fires both when the combo box is opened and when it is closed. If this sub executes when the combo box is closing, the code that clears the combo box causes the user's selection to be erased.
I'm trying to tell when the box is closed using the is_open variable, which alternates between true and false each time the event sub is executed. This seems like a brittle solution to the problem. Is there a better way?
You are on the right track by using the is_open boolean to track the state of the combo box, but what you really want to track is the state of "should I re-populate the combo box with database data?"
When do you want the list box populated? Currently, you want the list box to be populated every time the user clicks the drop-down box (not taking into account your is_open state variable). Is this really what you want?
I would imagine that what you really want is to have the combo box only update after something else changes. Perhaps you only want the drop down list to update when the form first opens. Maybe you only want the data to change when the text in a search box changes. If this is the case, you need to base your logic on the state of when you actually want to perform the update.
For example, let's say you want to update the combo box only if the text in a search box changes. I'm not looking at Excel at the moment, but let's pretend you have a text box called txtSearch with a Text property. I'd start by adding a module or class level variable to maintain the state of the previous text entry:
Private mPreviousSearchText As String
Then I'd update my event code like so:
Private Sub cboVariety_DropButtonClick()
Dim rs As New Recordset
Dim search_text As String
search_text = txtSearch.Text
If mPreviousSearchText = search_text Then
'The current search matches the previous search,'
'so we do not need to perform the update.'
Exit Sub
End If
cboVariety.Clear
cboVariety.AddItem search_text
If Len(search_text) > 2 Then
rs.Open _
"SELECT Name FROM tbl_Varieties " & _
"WHERE Name LIKE '%" & search_text & "%' " & _
"ORDER BY Name", connect_string, adOpenStatic
Do Until rs.EOF
If rs!Name <> search_text Then cboVariety.AddItem rs!Name
rs.MoveNext
Loop
rs.Close
End If
'Set the previousSearchText var to be the search_text so that it does'
'not run unless the value of my text box changes.'
mPreviousSearchText = search_text
End Sub
The entire point is to establish when you actually want to perform the update and find out a way to tie your logic decision to the state associated with when you want to perform the action, which is only coincidentally related to the user clicking on the drop-down box.
I found a simple way to solve this. It doesn't seem like it should work, but if I just reassign the value of the combo box after rebuilding the list, it doesn't discard the value that is selected.
Private Sub cboVariety_DropButtonClick()
Static search_text As String
Dim rs As New Recordset
If search_text = cboVariety Then Exit Sub
search_text = cboVariety
cboVariety.Clear
If Len(search_text) > 2 Then
rs.Open _
"SELECT Name FROM tbl_Varieties " & _
"WHERE Name LIKE '%" & search_text & "%' " & _
"ORDER BY Name", connect_string, adOpenStatic
Do Until rs.EOF
cboVariety.AddItem rs!Name
rs.MoveNext
Loop
rs.Close
End If
'' Reassign cboVariety in case this event was triggered by combo close
cboVariety = search_text
End Sub
This worked for me, instead of assigning the value, i assign the ListIndex property.
index = cb.ListIndex
cb.Clear
while condition
cb.AddItem item
Wend
If index < cbLinia.ListCount Then
cb.ListIndex = index
Else
cb.ListIndex = -1
End If
Use GotFocus() instead.
Private Sub ComboBox1_GotFocus()
MsgBox "caca"
End Sub
Triggers only when the combo get focus.
HTH