Data Array in Listbox?

M

Max

Help this noob out...

I want to place data in an array in a listbox. Then I want a user to select
one or multiple values within that text box.

1) How do I initialize the listbox?
2) How do populate the listbox with the array contents?
3) How do I store the user selection into another array?
 
B

Bernie Deitrick

Max,

Try the code below in the userform's codemodule. Assumes that you have a 2 column listbox named
Listbox1 on your userform, with its multiselect property set to multi.

HTH,
Bernie
MS Excel MVP

Option Explicit


Private Sub UserForm_Initialize()
'Populate the listbox with some values
Dim i As Integer
Dim j As Integer
Dim myArr(1 To 10, 1 To 2) As Integer

For i = 1 To 10
For j = 1 To 2
myArr(i, j) = i * 2 + IIf(j = 1, 100, 1)
Next j
Next i

Me.ListBox1.List = myArr
End Sub

'Get the selection of the listbox
Private Sub CommandButton1_Click()
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim mySel(1 To 10, 1 To 2) As Integer

i = 1

With Me.ListBox1
For k = 0 To .ListCount - 1
If .Selected(k) = True Then
mySel(i, 1) = Me.ListBox1.List(k, 0)
mySel(i, 2) = Me.ListBox1.List(k, 1)
i = i + 1
End If
Next k
End With

For j = 1 To i - 1
MsgBox "Selected " & mySel(j, 1) & ", " & mySel(j, 2)
Next j

End Sub
 

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