No question user-forms are enhancing the user experience if the users have to select, fill or search something in your application. A listbox is perfect to collect and present data, provide selection options to the user. You can do magical things with it. Lets look at how you can get the selected item index through a very simple example.
In the example we just simply populate item from a range listing capital letters from A to N then we will show the selected item index and value in a texbox at the bottom of the form.
Selection settings for a listbox
For a listbox you can set the selection option in listbox properties window using MultiSelect property:
Item index number Single selection
To get the index number of the selected item you can simply use .ListIndex property. It is important to highlight .ListIndex returns -1 if there is not a selected item.
YourListbox.ListIndexItem index number Multi Selection
In case multiple item selection allowed you have to loop through all the list items and capture/collect the index numbers one by one. You need to use .Selected property which is True if item is selected and False if it is not.
For i = 0 To YourListBox.ListCount - 1 If YourListBox.Selected[i] = True Then Debug.Print i End If Next iDownload[s]:
GetSelectedItemIndexListbox.xlsm
Tested:
- Windows 10/Office 365 Excel 2016 [32-bit]
Related link[s]:
VBA function to get index number for selected item from list type data validation
How to list/populate sheet names to a Listbox on a Userform
Populate Listbox items from range
Search as you type search box