ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Listbox Looping (https://www.excelbanter.com/excel-programming/375796-listbox-looping.html)

Bret

Listbox Looping
 
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

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


All times are GMT +1. The time now is 09:38 AM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com