Can't get listed of selected items from multiselect ListBox in Excel userform

无人久伴 提交于 2019-12-08 09:37:00

问题


New to VBA and having some difficulty getting selected items from a ListBox. I keep getting an error on the For line. The name of the ListBox is correct and I think .ListCount should work.

Sub GetListBox1()
Dim SelectedItems As String

For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected = True Then
    SelectedItems = SelectedItems & ListBox1.List(i)
    End If
Next i

Debug.Print SelectedItems

End Sub

回答1:


Try the code below, switch "UserForm1" with the name of your form.

Dim SelectedItems As String

With UserForm1 ' replace with the name of your form
    For i = 0 To .ListBox1.ListCount - 1
        If .ListBox1.Selected(i) = True Then  ' <-- you need to add the index of the selected item (according to the loop)
            SelectedItems = SelectedItems & .ListBox1.List(i)
        End If
    Next i
End With



回答2:


To Add commas in your output, try this...

Dim SelectedItems As String

With UserForm1 ' replace with the name of your form
    For i = 0 To .ListBox1.ListCount - 1
        If .ListBox1.Selected(i) = True Then  ' <-- you need to add the index of the selected item (according to the loop)
            SelectedItems = SelectedItems & .ListBox1.List(i) & ", " ' <-- THE COMMA goes here 
        End If
    Next i
End With

The way you did it in a ELSE clause would only add a comma if the listbox item was NOT selected, and WOULD add a comma for every listbox item that wasn't selected.

So If a user selected Alabama, and Montana from the states listbox choices, the output would show the two state names, plus 48 commas.




回答3:


Thanks @Sai Rado that worked. Trying to get them separated by commas but can’t get it to work.

Sub GetListBox1()
Dim SelectedItems As String
Dim SelectedCounter As Integer
SelectedCounter = 0

With UserForm1
    For i = 0 To .ListBox1.ListCount - 1
        If .ListBox1.Selected(i) = True Then
            SelectedCounter = SelectedCounter + 1
                If SelectedCounter = .ListBox1.Selected.ListCount Then
                    SelectedItems = SelectedItems & .ListBox1.List(i)
                Else
                    SelectedItems = SelectedItems & .ListBox1.List(i) & ", "
        End If
    Next i
End With
End Sub


来源:https://stackoverflow.com/questions/47195174/cant-get-listed-of-selected-items-from-multiselect-listbox-in-excel-userform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!