如何将列表框中的所有选定数据存储在 VBA 中的数组中

How to store all selected data from listbox in an array in VBA

我想知道是否有一种简单的方法可以将 ListBox 中的所有选定项目存储到数组中。

我尝试使用以下代码执行此操作,但没有成功。 FilterTest() return 我什么都没有。

Private Sub ListBox1_Change()

    Dim FilterTest() As Variant
    Dim myMsg As String
    Dim i As Long
    Dim Count As Integer


    Count = 1

    For i = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(i) Then

            ReDim Preserve FilterTest(Count)
            FilterTest(Count) = ListBox1.List(i)
            Count = Count + 1


        End If
    Next i

End Sub

你很接近。数组是以 0 为基数的集合(除非另有说明),因此从 0 开始计数。您也可以在声明变量时去掉括号。接下来,第一次重新调整变量,然后重新调整以在接下来的迭代中保留它。

Private Sub ListBox1_Change()

    Dim FilterTest As Variant
    Dim myMsg As String
    Dim i As Long
    Dim Count As Integer

    Count = 0

    For i = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(i) Then
            If Count = 0 Then
                Redim FilterTest(Count)
            Else
                Redim Preserve FilterTest(Count)
            End If
            FilterTest(Count) = ListBox1.List(i)
            Count = Count + 1
        End If
    Next i

End Sub