从列表框用户窗体中删除一行 [英] deleting a row from a listbox Userform
问题描述
我有一个列表框,显示一个Excel工作表的行,我需要添加一个删除按钮以删除选定的行.我尝试过了
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
但是当我尝试删除第10行时,就是删除的第9行,它总是删除所选行之前的行
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
任何修复???
谢谢大家
推荐答案
我必须自己对此进行测试,但我猜是这样的:
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.
这篇关于从列表框用户窗体中删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!