473,508 Members | 2,355 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Multiple list selection in search form

374 Contributor
Hi everyone,

I am using the following code adapted from Allen Browne:

Expand|Select|Wrap|Line Numbers
  1. 'Purpose:   This module illustrates how to create a search form, _
  2.             where the user can enter as many or few criteria as they wish, _
  3.             and results are shown one per line.
  4. 'Note:      Only records matching ALL of the criteria are returned.
  5. 'Author:    Allen Browne (allen@allenbrowne.com), June 2006.
  6. Option Compare Database
  7. Option Explicit
  8.  
  9. Private Sub cmdFilter_Click()
  10.     'Purpose:   Build up the criteria string form the non-blank search boxes, and apply to the form's Filter.
  11.     'Notes:     1. We tack " AND " on the end of each condition so you can easily add more search boxes; _
  12.                         we remove the trailing " AND " at the end.
  13.     '           2. The date range works like this: _
  14.                         Both dates      = only dates between (both inclusive. _
  15.                         Start date only = all dates from this one onwards; _
  16.                         End date only   = all dates up to (and including this one).
  17.     Dim strWhere As String                  'The criteria string.
  18.     Dim lngLen As Long                      'Length of the criteria string to append to.
  19.     Const conJetDate = "\#mm\/dd\/yyyy\#"   'The format expected for dates in a JET query string.
  20.  
  21.     '***********************************************************************
  22.     'Look at each search box, and build up the criteria string from the non-blank ones.
  23.     '***********************************************************************
  24.     'Text field example. Use quotes around the value in the string.
  25.    ' If Not IsNull(Me.txtDepartment) Then
  26.   '      strWhere = strWhere & "([Department] = """ & Me.txtDepartment & """) AND "
  27.    ' End If
  28.  
  29.     'Another text field example. Use Like to find anywhere in the field.
  30.     If Not IsNull(Me.txtRaisedBy) Then
  31.         strWhere = strWhere & "([Raised By] Like ""*" & Me.txtRaisedBy & "*"") AND "
  32.     End If
  33.  
  34.     'Number field example. Do not add the extra quotes.
  35.     If Not IsNull(Me.txtNCCID) Then
  36.         strWhere = strWhere & "([NCC ID Number] = " & Me.txtNCCID & ") AND "
  37.     End If
  38.  
  39.     'Yes/No field and combo example. If combo is blank or contains "ALL", we do nothing.
  40.   '  If Me.txtDepartmemt = -1 Then
  41.     '    strWhere = strWhere & "([Department] = True) AND "
  42.    ' ElseIf Me.txtDepartment = 0 Then
  43.     '    strWhere = strWhere & "([Department] = False) AND "
  44.    ' End If
  45.  
  46.     'Date field example. Use the format string to add the # delimiters and get the right international format.
  47.     If Not IsNull(Me.txtDate) Then
  48.         strWhere = strWhere & "([Date] >= " & Format(Me.txtDate, conJetDate) & ") AND "
  49.     End If
  50.  
  51.     'Another date field example. Use "less than the next day" since this field has times as well as dates.
  52.     'If Not IsNull(Me.txtEndDate) Then   'Less than the next day.
  53.    '     strWhere = strWhere & "([EnteredOn] < " & Format(Me.txtEndDate + 1, conJetDate) & ") AND "
  54.    ' End If
  55.  
  56.     '***********************************************************************
  57.     'Chop off the trailing " AND ", and use the string as the form's Filter.
  58.     '***********************************************************************
  59.     'See if the string has more than 5 characters (a trailng " AND ") to remove.
  60.     lngLen = Len(strWhere) - 5
  61.     If lngLen <= 0 Then     'Nah: there was nothing in the string.
  62.         MsgBox "No criteria", vbInformation, "Nothing to do."
  63.     Else                    'Yep: there is something there, so remove the " AND " at the end.
  64.         strWhere = Left$(strWhere, lngLen)
  65.         'For debugging, remove the leading quote on the next line. Prints to Immediate Window (Ctrl+G).
  66.         'Debug.Print strWhere
  67.  
  68.         'Finally, apply the string as the form's Filter.
  69.         Me.Filter = strWhere
  70.         Me.FilterOn = True
  71.     End If
  72. End Sub
  73.  
  74. Private Sub cmdReset_Click()
  75.     'Purpose:   Clear all the search boxes in the Form Header, and show all records again.
  76.     Dim ctl As Control
  77.  
  78.     'Clear all the controls in the Form Header section.
  79.     For Each ctl In Me.Section(acHeader).Controls
  80.         Select Case ctl.ControlType
  81.         Case acTextBox, acComboBox
  82.             ctl.Value = Null
  83.         Case acCheckBox
  84.             ctl.Value = False
  85.         End Select
  86.     Next
  87.  
  88.     'Remove the form's filter.
  89.     Me.FilterOn = False
  90. End Sub
  91.  
  92. Private Sub Form_BeforeInsert(Cancel As Integer)
  93.     'To avoid problems if the filter returns no records, we did not set its AllowAdditions to No.
  94.     'We prevent new records by cancelling the form's BeforeInsert event instead.
  95.     'The problems are explained at http://allenbrowne.com/bug-06.html
  96.     Cancel = True
  97.     MsgBox "You cannot add new clients to the search form.", vbInformation, "Permission denied."
  98. End Sub
  99.  
  100. Private Sub Form_Open(Cancel As Integer)
  101.     'Remove the single quote from these lines if you want to initially show no records.
  102.     Me.Filter = "(False)"
  103.     Me.FilterOn = True
  104. End Sub
What I am trying to get my head around is how would I code within the filter script to be able to filter based on multiple/single or no selections within a list box I have created.

The list box contains "Departments", so their names. If I select Blading and Projects, I want the filter to only display records for those two departments.

As you can see in the code I have commented out a couple of attempts with no luck and I dont want to be going around in circles for too long without any help.

I have named the list box lstDepartment.

Thanks for any help,

Chris
May 7 '10 #1
8 4508
Megalog
378 Recognized Expert Contributor
@munkee
What's the name of your list box control? Is it bound to a numeric value, or the department text value (are you using a single column, or multiple columns)? What we'll need to do is loop through all the selections and build a big OR string out of them.
May 7 '10 #2
Megalog
378 Recognized Expert Contributor
This should work in the script by Allen Browne, place it anywhere in the function where it is building the strWhere string. Make sure the lisbox is set to Extended type (for muliple selections). Replace "lstDeptFilter" & "[Department]" with your list control name and your Department field name.

First column is bound to a text value
Expand|Select|Wrap|Line Numbers
  1. 'Listbox example.
  2.     If Me.lstDeptFilter.ItemsSelected.Count > 0 Then
  3.         Dim itm As Variant
  4.         Dim strList As String
  5.         For Each itm In Me.lstDeptFilter.ItemsSelected
  6.             If strList = "" Then
  7.                 strList = "([Department] = '" & Me.lstDeptFilter.Column(0, itm) & "')"
  8.             Else
  9.                 strList = strList & " OR " & "([Department] = '" & Me.lstDeptFilter.Column(0, itm) & "')"
  10.             End If
  11.         Next
  12.         strWhere = strWhere & "(" & strList & ") AND "
  13.     End If
First Column is bound to a numeric value:
Expand|Select|Wrap|Line Numbers
  1. 'Listbox example.
  2.     If Me.lstDeptFilter.ItemsSelected.Count > 0 Then
  3.         Dim itm As Variant
  4.         Dim strList As String
  5.         For Each itm In Me.lstDeptFilter.ItemsSelected
  6.             If strList = "" Then
  7.                 strList = "([Department] = " & Me.lstDeptFilter.Column(0, itm) & ")"
  8.             Else
  9.                 strList = strList & " OR " & "([Department] = " & Me.lstDeptFilter.Column(0, itm) & ")"
  10.             End If
  11.         Next
  12.         strWhere = strWhere & "(" & strList & ") AND "
  13.     End If
May 7 '10 #3
munkee
374 Contributor
Thank you for the code Megalog I will try and implement it at work on Monday.

Whilst you are viewing, I have also been trying to clear selections from the list whenever I press the reset button which is situated in the code at this point: Private Sub cmdReset_Click().

What is the convention you use to clear a list box? is it acList or ListBox for my case?
May 7 '10 #4
Megalog
378 Recognized Expert Contributor
Updated Reset Code:

Expand|Select|Wrap|Line Numbers
  1. Private Sub cmdReset_Click() 
  2.     'Purpose:   Clear all the search boxes in the Form Header, and show all records again. 
  3.     Dim ctl As Control 
  4.  
  5.     'Clear all the controls in the Form Header section. 
  6.     For Each ctl In Me.Section(acHeader).Controls 
  7.         Select Case ctl.ControlType 
  8.         Case acTextBox, acComboBox 
  9.             ctl.Value = Null 
  10.         Case acCheckBox 
  11.             ctl.Value = False 
  12.         Case acListBox
  13.             call ClearList(ctl.Name)
  14.         End Select 
  15.     Next 
  16.  
  17.     'Remove the form's filter. 
  18.     Me.FilterOn = False 
  19. End Sub 

Place this function anywhere, it will clear the listbox when called from the Reset code.
Expand|Select|Wrap|Line Numbers
  1. Public Function ClearList(lst As ListBox)
  2.     Dim varItem As Variant
  3.  
  4.     If lst.MultiSelect = 0 Then
  5.         lst = Null
  6.     Else
  7.         For Each varItem In lst.ItemsSelected
  8.             lst.Selected(varItem) = False
  9.         Next
  10.     End If
  11.  
  12. End Function
May 7 '10 #5
munkee
374 Contributor
Appreciate the hard work I will put some feedback up on Monday, Thanks.
May 7 '10 #6
munkee
374 Contributor
Just tried the code and it works like a charm thanks!
May 10 '10 #7
Megalog
378 Recognized Expert Contributor
Glad it all worked for you!

Welcome to Bytes!
May 10 '10 #8
orkun
1 New Member
hi Dears,

I have included Megalog's ocde into the code which I have also taken from Allen Brown, but it brings no records. My list box name is "lst_status" and it should bring records with 2 different status. what am I doing wrong?

'Purpose: Build up the criteria string form the non-blank search boxes, and apply to the form's Filter.

Dim strWhere As String 'The criteria string.
Dim lngLen As Long 'Length of the criteria string to append to.
Dim strReport As String
Const conJetDate = "\#mm\/dd\/yyyy\#" 'The format expected for dates in a JET query string.

strReport = "Incident_Summary_Report_Between_Dates" 'Put your report name in these quotes.

If Not IsNull(Me.txtStartDate) Then
strWhere = strWhere & "([ReportDate] >= " & Format(Me.txtStartDate, conJetDate) & ") AND "
End If

If Not IsNull(Me.txtEndDate) Then
strWhere = strWhere & "([ReportDate] <= " & Format(Me.txtEndDate, conJetDate) & ") AND "
End If

If Not IsNull(Me.txtsapno) Then
strWhere = strWhere & "([SAPNo] Like ""*" & Me.txtsapno & "*"") AND "
End If


If Not IsNull(Me.observation_cbo) Then
strWhere = strWhere & "([Observation] = """ & Me.observation_cbo & """) AND "
End If

'Listbox example.
If Me.lst_status.ItemsSelected.Count > 0 Then
Dim itm As Variant
Dim strList As String
For Each itm In Me.lst_status.ItemsSelected
If strList = "" Then
strList = "([Status] = '" & Me.lst_status.Column(0, itm) & "')"
Else
strList = strList & " OR " & "([Status] = '" & Me.lst_status.Column(0, itm) & "')"
End If
Next
strWhere = strWhere & "(" & strList & ") AND "
End If

lngLen = Len(strWhere) - 5
If lngLen <= 0 Then 'Nah: there was nothing in the string.
MsgBox "No criteria", vbInformation, "Nothing to do."
Else 'Yep: there is something there, so remove the " AND " at the end.
strWhere = Left$(strWhere, lngLen)

If CurrentProject.AllReports(strReport).IsLoaded Then
DoCmd.Close acReport, strReport
End If

DoCmd.OpenReport strReport, acViewPreview, , WhereCondition:=strWhere
DoCmd.Close acForm, "msearch_frm", acSavePrompt
End If
Jan 20 '21 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2066
by: Ringwraith | last post by:
Hi! Have anyone ever tried to modify the Gene Cash's Tkinter tree widget (available from http://home.cfl.rr.com/genecash/) so it supports multiple items selection ( selection of multiple files...
0
3484
by: starace | last post by:
I have designed a form that has 5 different list boxes where the selections within each are used as criteria in building a dynamic query. Some boxes are set for multiple selections but these list...
1
1281
by: Kevin Murphy | last post by:
I receive the error message "Try to compose a less restrictive search query or check spelling" regardless of search term when attempting to search the list "PgSQL - General" via the mailing list...
9
16065
by: lightning | last post by:
Hi all, I'm not very conversant with the vocabulary of Access, so please ask for clarification if necessary... I am trying to build a search form that allows combinations of search terms. For...
2
2078
by: Prashant | last post by:
Hi All, we are using <input id="testFile" runat="server" type="file" /> control to select file from local machine. A problem with this control is at a time we can select only single file from...
1
4130
by: jcf378 | last post by:
Hi all-- Does anyone have any insight as to how I might create a search form that allows a user to select criteria based on any related table in the whole database. The search form I have now only...
11
5571
by: woodey2002 | last post by:
This problem is driving me crazy. Hello there, i am trying to create a search form for records in my access database. The search form will contain text boxes and a multi select list box. The user...
2
2734
by: woodey2002 | last post by:
Hi Guys and thanks for your time. I have a search form for my database that allows users to select multiple criteria from multi select list boxes. I successfully integrated a multi select...
6
4653
by: woodey2002 | last post by:
Hi Everyone. Thanks for your time. I am trying to create a search form that will allow users to select criteria from multiple multi select boxes. So far i have managed to achieve a search option...
2
3015
by: hollinshead | last post by:
hi there, i have been having this issue for quite some time now and i cant seem to get my head around it. I am trying to create a database for candidates CV's and covering letters. basically the data...
0
7118
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7323
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
4706
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3192
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3180
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1550
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
415
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.