Making WHERE statement from multiselect ListBox

J

John S. Ford, MD

I have a ListBox with its "Multiselect" property turned on. I want to use
the choices to create a WHERE statement for a separate form that uses the
same underlying datasource as the ListBox.

How can I code this using Access 2000?

John
 
D

Dirk Goldgar

John S. Ford said:
I have a ListBox with its "Multiselect" property turned on. I want to use
the choices to create a WHERE statement for a separate form that uses the
same underlying datasource as the ListBox.

How can I code this using Access 2000?


Usually you'll do this by looping through the list box's ItemsSelected
collection, cross-referencing that against the ItemData collection, and
building a comma-delimited list to be used with an In() predicate. Like
this:

'----- start of example code -----

Dim strCriteria As String
Dim strList As String
Dim varItem As Variant

With Me.lstMyListbox

Select Case .ItemsSelected.Count

Case 0
' Nothing selected, hence no criteria
strCriteria = ""

Case 1
' Only one item select, hence a simple "Where field ="
clause
strCriteria = "YourFieldName=" &
..ItemData(.ItemsSelected(0))

Case Else
' Build "Where file In()" clause
For Each varItem In .ItemsSelected
strList = strList & ", " & .ItemData(varItem)
Next varItem

strCriteria = "YourFieldName In(" & Mid(strList, 3) & ")"

End Select

End With

' Open form using the criteria string.
DoCmd.OpenForm "YourFormName", WhereCondition:=strCriteria

'----- end of example code -----

Note: the above code assumes that the field to be filtered on is numeric.
If it's text, then quotes have to be built into the criteria string
surrounding each selected field value.

Also note that this is untested air code.
 
J

John S. Ford, MD

Thanks Dirk. I'm going to study your code but it sounds like exactly what
I'm looking for.

John
 
J

John S. Ford, MD

Thanks Ken. I'll check that out. I've actually been experimenting with
using multiselect ListBoxes as described in your book. You cite an example
that creates a string used to fill a TextBox based on the selection of a
ListBox. Now I'm trying to understand how to go from there to filtering the
underlying datasource of a form.

John
 
K

Ken Snell MVP

To filter the underlying data source of a form, easiest way is to build a
WHERE clause, then set the form's RecordSource property to the original
unfiltered SQL statement plus the WHERE clause, in order to filter the data.
--

Ken Snell
<MS ACCESS MVP>
http://www.accessmvp.com/KDSnell/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top