Listbox questions

R

Robert Crandal

If I add like 20 items to my userform's listbox control, how can I
determine if a user selects or double clicks on item 10?? I'm
just trying to figure out which event handles when an item is
selected or double clicked.

Thank you
 
J

JLGWhiz

Assuming your listbox is ListBox1, if you use:

Private Sub ListBox1_Click()
MsgBox "You Selected" & Me.ListBox1.Value
End Sub

The above code would display a message box that tells you what selection you
made, if the ListBox1 is not a multiselect type.
 
D

Dave Peterson

I'm not quite sure what you're looking for, but you could use the .value and/or
the .listindex and the .list properties and the _click event--if you only allow
a single selection.

If you allow multiselection, you could use the _change event. (Actually, you
could use the _change event in both single/multi selection cases.

Option Explicit
Private Sub ListBox1_Click()
With Me.ListBox1
MsgBox .Value & vbLf & .ListIndex _
& vbLf & .List(.ListIndex)
End With
End Sub

or
Option Explicit
Private Sub ListBox1_Change()
With Me.ListBox1
If .ListIndex > -1 Then
MsgBox .ListIndex _
& vbLf & .Selected(.ListIndex) _
& vbLf & .List(.ListIndex)
End If
End With
End Sub

========
But I'm not sure I'd use either of these events. I find it more usual (as a
user) to allow me to pick and choose the selection(s) I want. I can change my
mind lots of times before I commit my choice.

And I usually have to hit an ok commandbutton to tell the program that I'm done.

With a single selection:
Option Explicit
Private Sub CommandButton1_Click()

With Me.ListBox1
If .ListIndex < 0 Then
MsgBox "nothing chosen"
Else
MsgBox .ListIndex & vbLf & .Value & vbLf & .List(.ListIndex)
End If
End With
End Sub
Private Sub UserForm_Initialize()
Dim iCtr As Long

With Me.ListBox1
.Clear
.MultiSelect = fmMultiSelectSingle
For iCtr = 1 To 20
.AddItem "A" & iCtr
Next iCtr
End With

Me.CommandButton1.Caption = "Ok"
End Sub

With multiselect:

Option Explicit
Private Sub CommandButton1_Click()

Dim iCtr As Long


With Me.ListBox1
For iCtr = 0 To .ListCount - 1
If .Selected(iCtr) Then
MsgBox iCtr & vbLf & .List(iCtr)
End If
Next iCtr
End With
End Sub
Private Sub UserForm_Initialize()
Dim iCtr As Long

With Me.ListBox1
.Clear
.MultiSelect = fmMultiSelectMulti
For iCtr = 1 To 20
.AddItem "A" & iCtr
Next iCtr
End With

Me.CommandButton1.Caption = "Ok"
End Sub

Again, you can actually use the loop with the single selection, but why bother.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top