I have a list box in Access with the mult-select value set to true. I want to be able to set the selected values through VBA code. How would I go about doing this?
2 Answers
Use the .Selected method, and pass the index value of the item you want to select.
'Populate the listbox (probably you are doing this elsewhere):
'Select items items 1 and 2 (remembering ListBox is 0-index, so this selects the 2nd and 3rd items in the list:
ListBox1.Selected(1) = True
ListBox1.Selected(2) = True
Also, make sure the .MultiSelect = fmMultiSelectMulti or .MultiSelect = fmMultiSelectExtended.
4 Comments
Fionnuala
MS Access populate the list box is usually
listbox.RowSource="SELECT ID, Item FROM Table"Fionnuala
I could complain about those constants too :)
DasPete
Awesome! Thanks @David Zemens, so if I wanted to select the values based off their content I assume I would have to loop through all items to find the correct row number and then use that value in the
.Selected methodDavid Zemens
@loveforvdubs Yep. There may be a better way that I'm not aware of, but that's how I do it.
Just as an additional note to the above. Let us say I have a Region listbox where a user selects various regions, then this code might be used to select hospitals from multi-select listbox HospCounty based on the fifth column (4, counting from zero) matching the region selected.
For Each itm In Me.Region.ItemsSelected
For i = 0 To Me.HospCounty.ListCount - 1
If Trim(Me.HospCounty.Column(4, i)) = Trim(Me.Region.Column(0, itm)) Then
Me.HospCounty.Selected(i) = True
End If
Next
Next