Passing multiselections from listbox to sub

G

Guest

I have a listbox where the selected item is passed to a sub:

NewSub(listbox1.Value)

I want to turn on the multiselect and pass all selected values to the same
sub. Is the only way of doing this by sending the multiselect items to an
array and pass the array to the sub?

If so, how do you pass the items from the listbox to the array.

Thanks

EM
 
D

Dave Peterson

That seems like a reasonable approach to me.

Another option would be to just pass the listbox itself to the other function.
And look for the selected items there.

The first option...

I created a userform with a listbox and two command buttons on it. All this
code was behind the userform:

Option Explicit
Private Sub CommandButton1_Click()
Unload Me
End Sub
Private Sub CommandButton2_Click()
Dim iCtr As Long
Dim sCtr As Long
Dim myArr() As String
With Me.ListBox1
ReDim myArr(0 To .ListCount - 1)
sCtr = -1
For iCtr = 0 To .ListCount - 1
If .Selected(iCtr) Then
sCtr = sCtr + 1
myArr(sCtr) = .List(iCtr)
End If
Next iCtr
End With

If sCtr = -1 Then
'nothing selected, don't call anything
Beep
Else
ReDim Preserve myArr(0 To sCtr)
Call NewFunction(myArr)
End If
End Sub
Private Sub UserForm_Initialize()
Dim iCtr As Long
Me.ListBox1.MultiSelect = fmMultiSelectMulti
For iCtr = 1 To 10
Me.ListBox1.AddItem "asdf" & iCtr
Next iCtr
End Sub
Function NewFunction(myArr() As String)
Dim iCtr As Long
For iCtr = LBound(myArr) To UBound(myArr)
MsgBox myArr(iCtr)
Next iCtr
End Function

=======
The alternative--passing the listbox itself (with the same userform):

Option Explicit
Private Sub CommandButton1_Click()
Unload Me
End Sub
Private Sub CommandButton2_Click()
Call NewFunction(Me.ListBox1)
End Sub
Private Sub UserForm_Initialize()
Dim iCtr As Long
Me.ListBox1.MultiSelect = fmMultiSelectMulti
For iCtr = 1 To 10
Me.ListBox1.AddItem "asdf" & iCtr
Next iCtr
End Sub
Function NewFunction(myListbox As MSForms.ListBox)
Dim iCtr As Long
With myListbox
For iCtr = 0 To .ListCount - 1
If .Selected(iCtr) Then
MsgBox .List(iCtr)
End If
Next iCtr
End With
End Function
 

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