Jason
Jason

Reputation: 650

Get text of listBox.selectedItems?

I have a listBox that displays members of a distribution group. I have the listbox setup for multisimple selection to select more than one member. I'm trying to do a loop to get the text of the selected items(index's). Here is my code which works fine for the first item. On the second item it crashes and says "Index was outside the bounds of the array." I will be taking these members and placing them in the To: field of a meeting request. So I need to to be formatted like this: member1;member2. I'm just using the MsgBox to test what I'm getting back. But I'm guessing I would need to add to an array. Please help!

For i = 0 To (myListBox.Items.Count - 1)
        If myListBox.GetSelected(i) Then
            MsgBox(myListBox.SelectedItems(i))
        End If
    Next

Upvotes: 2

Views: 19039

Answers (2)

Chrismas007
Chrismas007

Reputation: 6105

Re-read the question and I think you want to store this as a string. This should do what you are looking for:

Documentation on ListBox.Selected()

Dim MailStr as String

MailStr = ""

If myListBox.SelectedItems.Count = 0 Then
    MsgBox "No User Selected"
    Exit Sub
End If
For i = 0 to (myListBox.Items.Count - 1)
    If myListBox.Selected(i) Then
        MailStr = MailStr & myListBox.Items.Item(i) & "; "
    End If
Next i

You can also try:

Dim assets As String 

 assets = ""

 For Each item In assetListBox.SelectedItems
        If assets = Nothing Then
            assets = item
            'Outputs 1 item "Member1"
            MsgBox(assets)
        Else
            assets = assets & "; " & item
            'Outputs 2 items in format "member1; member2"
            MsgBox(assets)
        End If
    Next

Upvotes: 2

Jason
Jason

Reputation: 650

This is what worked the way I want it.

Dim assets As String 

 assets = ""

 For Each item In assetListBox.SelectedItems
        If assets = Nothing Then
            assets = item
            'Outputs 1 item "Member1"
            MsgBox(assets)
        Else
            assets = assets & "; " & item
            'Outputs 2 items in format "member1; member2"
            MsgBox(assets)
        End If
    Next

Upvotes: 0

Related Questions