VBA新手,在从ListBox中获取所选项目时遇到一些困难。我一直在For line上收到错误。 ListBox的名称是正确的,我认为.ListCount应该可以工作。
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
答案 0 :(得分:1)
尝试以下代码,使用表单名称切换"UserForm1"
。
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
答案 1 :(得分:1)
要在输出中添加逗号,请尝试此操作...
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
在ELSE子句中执行此操作的方式只会在未选中列表框项时添加逗号,并且为每个未选中的列表框项添加逗号。
因此,如果用户从州列表框选项中选择了Alabama和Montana,则输出将显示两个州名称,以及48个逗号。
答案 2 :(得分:0)
感谢@Sai Rado工作。试图用逗号分隔它们但不能使它工作。
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