Determining multiple selections in a List Box

Normally, a ListBox's MultiSelect property is 0, which means that the user can select only one item in the ListBox.

If the ListBox allows multiple selections (that is, if its MultiSelect property is either 1 or 2), trying to access the Listlndex or Value properties will result in an error. Instead, you need to use the Selected property, which returns an array whose first item has an index of 0. For example, the following statement displays True if the first item in the ListBox list is selected:

MsgBox ListBox1.Selected(0)

The companion CD-ROM contains a workbook that demonstrates how to identify the selected item(s) in a ListBox. It works for single-selection and multiple-selection ListBoxes.

The following code, from the example workbook on the CD-ROM, loops through each item in the ListBox. If the item was selected, it appends the item's text to a variable called Msg. Finally, the names of all the selected items are displayed in a message box.

Private Sub OKButton_Click() Msg = ""

For i = 0 To ListBox1.ListCount - 1 If ListBox1.Selected(i) Then _

Next i

MsgBox "You selected: " & vbCrLf & Msg Unload Me End Sub

Figure 14-10 shows the result when multiple ListBox items are selected.

Figure 14-10: This message box displays a list of items selected in a ListBox.
0 0

Post a comment