[英]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.我有一个显示 Excel 工作表行的列表框,我需要添加一个删除按钮来删除所选行。 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但是当我尝试删除例如第 10 行时,第 9 行会被删除,它总是会删除所选行之前的行
any fix ???任何修复???
Thanks everyone谢谢大家
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.如果它不是多选,它会简化代码,因为不需要循环列表框。
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另请注意, Rows(i).Delete
与Rows(i).Select Selection.Delete
完全相同,但应尽可能避免Select
As said @BigBen :正如@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”声明将默认下限更改为 1 而不是 0。例如:
Option Base 1
Dim arValues(10) As String 'contains 10 items (not 11)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.