Thread: Listbox Looping
View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Dave Peterson Dave Peterson is offline
external usenet poster
 
Posts: 35,218
Default Listbox Looping

Is your listbox set up for multiselect = fmMultiSelectMulti and you want to get
the selected items?

This worked for me to get an array of the selected items:

Option Explicit
Private Sub CommandButton1_Click()
Dim iCtr As Long
Dim sCtr As Long
Dim myArr() As String

With Me.ListBox1
ReDim myArr(0 To .ColumnCount - 1, 0 To .ListCount - 1)

sCtr = -1
For iCtr = 0 To .ListCount - 1
If .Selected(iCtr) = True Then
sCtr = sCtr + 1
myArr(0, sCtr) = .List(iCtr, 0)
myArr(1, sCtr) = .List(iCtr, 1)
End If
Next iCtr

If sCtr = -1 Then
MsgBox "Nothing selected!"
Else
ReDim Preserve myArr(0 To .ColumnCount - 1, 0 To sCtr)
'prove that it worked
For iCtr = 0 To sCtr
MsgBox myArr(0, iCtr) & "--" & myArr(1, iCtr)
Next iCtr
End If

End With
End Sub
Private Sub UserForm_Initialize()

Dim iCtr As Long

With Me.ListBox1
.MultiSelect = fmMultiSelectMulti
.ColumnCount = 2
For iCtr = 0 To 9
.AddItem "A" & iCtr
.List(iCtr, 1) = "B" & iCtr
Next iCtr
End With
End Sub


Bret wrote:

I have a listbox with 2 columns. First column is EmployeeID and second column
is Employee name. what is the best way to loop thru this list box and
capture each ID and name in a variable?

thanks for your assistance.


--

Dave Peterson