Determining the selected item

The examples in 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


MsgBox ListBox1.Value

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 Listlndex property will return -1.

The numbering of items in a ListBox begins with 0—not 1. Therefore, the Listlndex of the first item is 0, and the Listlndex of the last item is equivalent to the value of the ListCount property less 1.

Was this article helpful?

0 0

Post a comment