Excel - How to get the index in VBA of the selected item in a ListBox

Asked By Stefan Mueller on 16-Jul-07 12:29 PM
I'd like to get the index of the selected item in a ListBox in VBA.
In real VB I do it with the following code:

Private Declare Function SendMessage Lib "user32" Alias
As Long, lParam As Any) As Long

Private Sub UserForm_Initialize()
Dim Counter As Long


For Counter = 1 To 20
ListBox1.AddItem "MyItem " & Counter

CommandButton1.Caption = "Index of selected Item"
End Sub

Private Sub CommandButton1_Click()
MsgBox (SendMessage(ListBox1.hWnd, &H19F, 0, 0))
End Sub

But how can I do it in VBA (e.g. Excel)?

Chip Pearson replied on 16-Jul-07 12:41 PM
Just use the ListIndex property of the ListBox control. It will be -1 if no
item is selected. It is the same as real VB. Why do you jump through the
hoops with SendMessage in the first place?

With Me.ListBox1
If .ListIndex < 0 Then
Debug.Print "No item selected"
Debug.Print "Item: " & CStr(.ListIndex), .List(.ListIndex)
End If
End With

Chip Pearson
Microsoft MVP  - Excel
Pearson Software Consulting
(email on the web site)
Gary Keramidas replied on 16-Jul-07 12:53 PM

what would be the difference in using either of these? they both seem to return
the same result.




Bob Phillips replied on 16-Jul-07 01:01 PM
There is no difference in the result. The former is most useful when
retrieving a secondary column from the list.



(there's no email, no snail mail, but somewhere should be gmail in my addy)
Gary Keramidas replied on 16-Jul-07 02:19 PM
ok, i see.
thanks, bob