【问题标题】:How to get all item selected into ListBox ( Multiple Selection ) in VBA如何在 VBA 中将所有项目选择到列表框(多选)中
【发布时间】:2019-06-13 15:44:02
【问题描述】:

我想从一个列表框中选择多个数据

以下代码适用于单选:0 -fmMultiSelectSingle

Private Sub ListBox1_Click()
    Dim Msg As String
    Dim i As Integer

    Msg = "You selected:" & vbNewLine
    For i = 1 To ListBox1.ListCount
        If ListBox1.Selected(i) Then
            Msg = Msg & ListBox1.List(i) & vbNewLine                         
        End If
    Next i

    MsgBox Msg
    ListBox1.Selected(0) = False
End Sub

消息框向我显示选择的项目,但如果我将 MultiSelect 选项切换为:

1 - fmMultiSelectMulti2 - fmMultiSelectExtended,前面的代码不起作用:消息框不显示任何内容。

我做错了吗?

【问题讨论】:

  • @Vityata 下一个错误恢复是处理如果选择了此列表框的一个项目然后取消选择其他列表框的其他项目的错误。我编辑了我的帖子,所以没有混淆可能。谢谢
  • 这样问题似乎更好:)
  • 我必须从 0 开始,到 listbox1.count-1 结束

标签: excel vba listbox multi-select


【解决方案1】:

事件应该是_Change而不是_Click,只要它没有进入它,在fmMultiSelectExtended的情况下由于一些奇怪的原因。或者尝试 VBE 中的其他内置事件,可从下拉列表中获得:

Private Sub ListBox1_Change()

    Dim myMsg As String
    Dim i As Long

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

    Debug.Print myMsg

End Sub

请考虑一个事实,如果您依次选择 3 个值,则每次只有 1 个选定值。因此,您将在即时窗口中获得 3 组不同的数据。像这样:

为此ListBox

【讨论】:

  • @Viyata 谢谢,但是有没有办法将所有选定的项目存储到一个数组中?我试过这个:Dim Filtre() As Variant Count = 1' Before the loop ReDim Preserve Filtre(Count) ' In the For If Filtre(Count) = ListBox1.List(i)'In the For If Count = Count + 1'In the For If 但这绝对行不通
  • @Dorian - 应该有办法,我现在很喜欢,但问一个新问题,你可能会得到一个很好的答案。
【解决方案2】:

以下代码将所选项目的所有值存储在列表框中

Public Function listASIN() As String
Dim ctl As Control
Dim strASIN As String

Set ctl = Me!lstASIN

strASIN = ""

' Now select what records from listbox
If ctl.ItemsSelected.Count > 0 Then
    i = 1
    For Each varItem In ctl.ItemsSelected
        strASIN = strASIN & ctl.ItemData(varItem) & ","
        i = i + 1
    Next varItem
Else
    Exit Function
End If

'Remove Last "," from ASIN list
strASIN = Left(strASIN, Len(strASIN) - 1)

listASIN = strASIN
End Function

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 2013-01-23
    相关资源
    最近更新 更多