TenEM
TenEM

Reputation: 127

deleting a row from a listbox Userform

I have a listbox that shows up the rows of an excel sheet i need to add a delete button to delete the selected row. i tried this

Private Sub CommandButton3_Click()
Dim i As Integer

For i = 0 To Range("A65356").End(xlUp).Row - 1
    If lstDisplay.Selected(i) Then
        Rows(i).Select
        Selection.Delete
    End If
Next i
End Sub

but when i try to delete for example the the row 10 it's the 9 that gets deleted it always delets the line before the one selected

any fix ???

Thanks everyone

Upvotes: 1

Views: 7035

Answers (2)

TourEiffel
TourEiffel

Reputation: 4414

I would suggest you this :

Private Sub CommandButton3_Click()
Dim i As Integer

For i = 1 To Range("A65356").End(xlUp).Row - 1
    If lstDisplay.Selected(i) Then
        Rows(i).Delete
        i = i - 1
    End If
Next i
End Sub

Also Note that Rows(i).Delete is exactly the same as Rows(i).Select Selection.Delete Excepted that Select should be avoided as much as possible

As said @BigBen :

You can use the "Option Base 1" declaration at the top of a code module to change the default lower bound to 1 instead of 0. For exemple :

Option Base 1 

Dim arValues(10) As String       'contains 10 items (not 11)  

Option Base Doc Here

Upvotes: 1

JvdV
JvdV

Reputation: 75840

I'll have to test this myself, but I guess something along the lines of:

Private Sub CommandButton3_Click()

Dim i As Long, rng As Range
With Me.lstDisplay
    For i = 0 To .ListCount - 1
        If .Selected(i) Then
            If Not rng Is Nothing Then
                Set rng = Union(rng, Sheets("Sheet1").Rows(i + 1))
            Else
                Set rng = Sheets("Sheet1").Rows(i + 1)
            End If
        End If
    Next i
End With

rng.EntireRow.Delete

End Sub

That way you'll only have to perform deleting rows once.

Btw, I anticipated a multiselect listbox. If it's not a multiselect it would simplify the code as there is no need to loop the listbox.

Upvotes: 2

Related Questions