Home » excel » excel – How to store all selected data from listbox in an array in VBA

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

Posted by: admin May 14, 2020 Leave a comment

Questions:

I would like to know if there is a simple way to store all selected item from a ListBox into an array.

I tried to do this with the following code, but it didn’t work has excepted.
FilterTest() return me nothing.

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
How to&Answers:

You were close. Arrays are base 0 collections (unless specified otherwise) so start counting with 0. You can also drop the parentheses when declaring the variable. Next, redim the variable the first time and then redim preserve it the following iterations.

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