无法从Excel用户窗体中的多选ListBox中列出所选项目

新的VBA和从列表框中获取选定的项目有一些困难。 我一直在For线上发生错误。 列表框的名称是正确的,我想.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 

尝试下面的代码,用您的窗体的名称切换"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 

在输出中添加逗号,试试这个…

 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子句中做的方式只会添加一个逗号,如果没有select列表框项目,并且会为每个没有被选中的列表框项目添加一个逗号。

所以如果用户从州列表框中select了阿拉巴马州和蒙大拿州,那么输出结果会显示两个州名和48个逗号。

谢谢@Sai雷达工作。 试图让他们分开逗号,但不能得到它的工作。

 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