vxs8122
vxs8122

Reputation: 844

How do I restart loop once it removes a nonselected item in a listbox?

On the listbox, an user has an option to add dates. I am trying to also give the user the option to remove dates by clicking on a button. My code looks like this:

Private Sub RemoveDate_Click()
    Dim objSpecifyDates As Object
    Dim i As Integer
    Set objSpecifyDates = ActiveSheet.OLEObjects("SpecifyDatesListBox").Object
    If objSpecifyDates.listCount = 0 Then
        Exit Sub
    Else
        For i = 0 To objSpecifyDates.listCount - 1
            If Not objSpecifyDates.Selected(i) Then
                objSpecifyDates.RemoveItem (i)
            End If
        Next
    End If
End Sub

The problem with this code is once an item is removed, it returns error at the last loop since that index became nonexistent. Is there a way to restart the loop once it removes an item?

Upvotes: 0

Views: 26

Answers (1)

Brad
Brad

Reputation: 12245

When removing things like this you need to move backwards through the collection.

For i = objSpecifyDates.listCount - 1 To 0 Step -1
    ...
Next i

Upvotes: 2

Related Questions