You will need to assign the SQL statement to the RecordSource property of the
subform and then requery it. To build the WHERE clause you itereate through
the ItemsSelected collections of the list boxes and build value lists in
code. The IN operator can then be used with the value lists.
You don't say how the selections from the two list boxes interrelate, so for
this example I'm assuming that you want the subform to return rows where one
field matches any selection in one list box AND another field matches any
selection in the other. If you want rows returned where one field matches
any selection in one list box OR another field matches any selection in the
other then just change the Boolean AND operator in the code to an OR. The
code would go something like this and would most likely be called from a
button on the main form. To illustrate how different data types are handled
one list box (lstSupplierID) is of numbers, the other (lstProducts) of text
items:
Dim varItem As Variant
Dim strSQL As String
Dim strSupplierIDList As String
Dim strProductList As String
Dim ctrl As Control
Dim frm As Form
Set ctrl = Me.lstSupplierID
' iterate through suppliers list box's ItemsSelected collection
' and build value list of numbers
If ctrl.ItemsSelected.Count > 0 Then
For Each varItem In ctrl.ItemsSelected
strSupplierIDList = strSupplierIDList & "," &
ctrl.ItemData(varItem)
Next varItem
' remove leading comma
strSupplierIDList = Mid(strSupplierIDList, 2)
End If
Set ctrl = Me.lstProducts
' iterate through suppliers list box's ItemsSelected collection
' and build value list of text values
If ctrl.ItemsSelected.Count > 0 Then
For Each varItem In ctrl.ItemsSelected
strProductList = strProductList & ",""" & ctrl.ItemData(varItem)
& """"
Next varItem
' remove leading comma
strProductList = Mid(strProductList, 2)
End If
' build SQL string
strSQL = "SELECT * FROM MyTable"
If Len(strSupplierIDList) > 0 Then
strSQL = strSQL & " WHERE SupplierID " & _
"IN(" & strSupplierIDList & ")"
End If
If Len(strSupplierIDList) > 0 Then
If Len(strProductList) > 0 Then
strSQL = strSQL & _
" AND Product IN(" & strProductList & ")" ' change this
line if
' a Boolean OR is required
End If
Else
If Len(strProductList) > 0 Then
strSQL = strSQL & _
" WHERE Product IN(" & strProductList & ")"
End If
End If
' add order by clause to sort subfrom by product
strSQL = strSQL & " ORDER BY Product"
' assign SQL statement to subform's RecordSource
' property and requery subform
Set frm = Me.MySubformControl.Form
frm.RecordSource = strSQL
frm.Requery
Note that MySubformControl here is the name of the subform control in the
main form's Controls collection, i.e. the control which houses the subform.
Ken Sheridan
Stafford, England