1
votes

So I have a userform that has a: listbox called "lstentries" radio button called "Delete". Also, the "Start" is the name of the cell that is the top left corner of the table of rows.

I already set the code so it can select multiple entries in the listbox. However, when I select multiple entries it only deletes the first row that it comes to. So i tried making a while loop so it keeps deleting the selected ones, but that's not working either. I get the "Run-time error '1004' - Method 'Range' of object'_Global' failed"

Hopefully someone can help me out. Here is the snippet of the code where it deletes the rows. Thanks in advance.

If optDelete.Value = True Then
        Dim delete As Range
        Do While True
            Set delete = Range("start").Offset(lstEntries.ListIndex, 0)
            delete.EntireRow.delete Shift:=xlUp
        Loop
    End If
2

2 Answers

0
votes

In the list box you can run through the list of items. Since you are allowing for multiple items to be selected and deleted, you will have to adjust the index as items are removed.

The list box is 0-indexed which means it starts at 0 and not 1.

' set the to go through all items in the list
For listIndexCount = 0 To lstEntries.ListCount

    ' check to make sure the index count is not greater or equal to the total number of items
    ' this is needed because the ListCount will change if items are deleted
    If listIndexCount >= lstEntries.ListCount Then
        Exit Sub
    End If

    ' check to see if the item is selected
    If lstEntries.Selected(listIndexCount) Then

        ' remove item
        lstEntries.RemoveItem (listIndexCount)

        ' subtract 1 to account for removed item
        listIndexCount = listIndexCount - 1
    End If
Next
0
votes

Another option in cases like this is to iterate through in reverse order. When starting at the bottom of the list you do not have to worry about adjusting the index since the items further up are not affected by removing an item below them.