2

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

After some debugging I have found a solution. I hope that helps for others. Each time I remove an item, as the ListCount value is updated, I make it go back to the beginning. Not good for performance but it is working.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.