Microsoft Office Tutorials and References
In Depth Information
This example, named listbox unique items1.xlsm , is available on the companion
CD-ROM. A workbook named listbox unique items2.xlsm has a slightly more
sophisticated version of this technique and displays the items sorted.
Determining the selected item in a ListBox
The examples in the preceding sections merely display a UserForm with a ListBox filled with
various items. These procedures omit a key point: how to determine which item or items were
selected by the user.
This discussion assumes a single-selection ListBox object — one whose MultiSelect
property is set to 0 .
To determine which item was selected, access the ListBox’s Value property. The statement that
follows, for example, displays the text of the selected item in ListBox1 .
If no item is selected, this statement will generate an error.
If you need to know the position of the selected item in the list (rather than the content of that
item), you can access the ListBox’s ListIndex property. The following example uses a message
box to display the item number of the selected ListBox item:
MsgBox “You selected item #” & ListBox1.ListIndex
If no item is selected, the ListIndex property will return –1 .
The numbering of items in a ListBox begins with 0 — not 1. Therefore, the ListIndex
of the first item is 0 , and the ListIndex of the last item is equivalent to the value of
the ListCount property less 1.
Determining multiple selections in a ListBox
A ListBox’s MultiSelect property can be any of three values:
h 0 ( fmMultiSelectSingle ): Only one item can be selected. This setting is the default.
h 1 ( fmMultiSelectMulti ): Pressing the spacebar or clicking selects or deselects an
item in the list.
h 2 ( fmMultiSelectExtended ): Shift-clicking extends the selection from the previously
selected item to the current item. You can also use Shift and one of the arrow keys to
extend the selected items.