To get the selected item you can use the Text and ListIndex property. They return the text and the index of the selected item respectively.
lSelectedText = List1.Text
where lSelectedText is a string variable which will contain the text of the currently selected item
lSelectedIndex = List1.ListIndex
where lSelectedIndex is a long variable which will contain the index of the currently selected item. Note that as index's start from 0, the first item on the list will return a ListIndex of 0. The following code displays a message box with the text and listindex of the current item
' Declare the variables
Dim gText As String
Dim gIndex As String
' Fill the variables
gText = List1.Text
gIndex = List1.ListIndex + 1
' Display the message box
Msgbox gText & ", item number " & gIndex & " is currently
selected.
To find if an item has been selected or checked when more than one item can be selected, you can use the Selected property. The following code loops through and displays a message box for each selected item
For i = 0 to list1.ListCount
If List1.Selected(i) = True Then
Msgbox "Selected Item: "
& List1.List(i)
End If
Next
For slightly more advanced users, you can also use the SendMessage API, which is much quicker, as you don't have to loop through all the items in the list box. First, declare the API call:
Private Declare Function SendMessage Lib "user32" _
Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg
_
As Long, ByVal wParam As Long, lParam As Any) As Long
As we want to gather the listbox's selected items, we'll send the LB_GETSELITEMS constant in the wMsg argument, which you declare like so:
Private Const LB_GETSELITEMS = &H191
Basically, the LB_GETSELITEMS message fills an array with the index numbers of all the selected items. So the API knows how much we want, and where we want it, we pass the maximum number of selected items in the 3rd parameter (we can use the listboxes SelCount property for this), and the first item in an array in the 4th. This array will then be filled with all the selected items. The code below calls the SendMessage API, gets the selected items, and displays a message box for each one of them.
Dim ItemIndexes() As Long, x As Integer, iNumItems As Integer
iNumItems = ThisBox.SelCount
If iNumItems Then
ReDim ItemIndexes(iNumItems - 1)
SendMessage ListBox1.hwnd, LB_GETSELITEMS, iNumItems, _
ItemIndexes(0)
End If
For x = 0 To iNumItems - 1
MsgBox ListBox1.List(ItemIndexes(x))
Next x
After being passed to the SendMessage function, iNumItems holds the total number of selected items, and the ItemIndexes array holds the selected item index values. Notice, that you must pass a pointer to the ItemIndexes array, and not the array itself. Thus, we passed ItemIndexes(0) into the SendMessage function, not ItemIndexes().
Comments