问题
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