【问题标题】:Can't get listed of selected items from multiselect ListBox in Excel userform无法从 Excel 用户表单中的多选 ListBox 中列出所选项目
【发布时间】:2017-11-18 09:05:14
【问题描述】:

VBA 新手,在从 ListBox 中获取选定项目时遇到一些困难。我在 For 行上不断收到错误消息。 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

【问题讨论】:

  • 此代码Sub GetListBox1 位于何处?它在User_form 模块内吗?什么功能或控件触发它?

标签: excel vba listbox userform


【解决方案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

【讨论】:

  • 谢谢,太好了!除了缺少我之外,我还将它放在一个模块而不是用户窗体中
  • 我无法获得所选项目的数量。我需要在它们之间加上逗号,但不是最后一个。这就是我所拥有的,但我在.ListBox1.Selected.ListCount 上收到“参数不是可选的”错误。这是错误的语法吗?
  • @bigbucky 我的代码中没有任何地方 .ListBox1.Selected.ListCount ,你从哪里得到这部分?
  • 对不起,我不是很清楚。你的代码工作得很好。我试图调整它以获得用逗号分隔的值,但无法弄清楚。见下文。
【解决方案2】:

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

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 子句中执行此操作的方式只会在未选择列表框项目时添加一个逗号,并且会为每个未选择的列表框项目添加一个逗号。

因此,如果用户从州列表框选项中选择阿拉巴马州和蒙大拿州,输出将显示两个州名,外加 48 个逗号。

【讨论】:

  • 谢谢,我花了一段时间,但我最终想通了。然后我只是从字符串中减去两个字符,所以最后没有多余的逗号。
【解决方案3】:

感谢@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多