Search code examples
vbalistboxlistboxitem

VBA - Remove empty items from ListBox


I want to remove empty items from the ListBox I have created with array. However at some point, as each time the ListCount value is updated, the code fails. How can I overcome this problem?

Private Sub RemoveEmptyRows(lst As msforms.ListBox)
With lst
    For i = 0 To .ListCount - 1
        If .List(i) = False Then
            .RemoveItem i
        End If
    Next
End With

End Sub


Solution

  • Try the next code, please:

    Private Sub RemoveEmptyRows(lst As msforms.ListBox)
        Dim i As Long
        With lst
            For i = .ListCount - 1 To 0 Step -1
                If .List(i) = Empty Then
                    .RemoveItem i
                End If
            Next
        End With
    End Sub
    

    The iteration must be done backwards. Otherwise, after items removing, their reference is lost...

    That's why your solution, even not very efficient, works. After each item removal the iteration is restarted with new references for all existing items.