如何将所有选定的项目都放入VBA的ListBox(多选)中

时间:2019-06-13 15:44:02

标签: excel vba listbox multi-select

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

以下代码适用于单选: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,以前的代码不起作用:消息框什么也不显示。

我做错什么了吗?

2 个答案:

答案 0 :(得分:0)

对于_Change,由于某种奇怪的原因,该事件应该是_Click,而不是fmMultiSelectExtended,只要它没有进入它就行。或尝试使用VBE中的其他内置事件,该事件可从下拉菜单中获得:

enter image description here

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组不同的数据。像这样:

enter image description here

为此ListBox

enter image description here

答案 1 :(得分:0)

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

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