0

我一直在开发一个用户窗体,它使用由 A 列填充的列表框来删除基于列表框选择的特定行。但是当我单击“应用”按钮时,它需要很长时间才能处理并删除行。

Apply 按钮的代码如下,UserForm 中几乎没有其他代码。只是我。隐藏在取消按钮中。

Private Sub CommandApply_Click()

Dim i As Long
Dim n As Long
Dim col As New Collection
Dim itm As Variant
Dim rng As Range

' First, collect the row numbers corresponding to the selected items
' We work from last to first
n = Me.ListBox1.ListCount
For i = n - 1 To 0 Step -1
    If Me.ListBox1.Selected(i) Then
    Else
        col.Add i + 1
    End If
Next i

' Then delete the rows
Set rng = Worksheets("Sheet1").Range("A1:A100")
For Each itm In col
    rng.Rows(itm).EntireRow.Delete
Next itm

 blnCancel = False
   Me.Hide
End Sub
4

1 回答 1

1

我认为您最好将未选择的项目收集到循环中的 Range 中,然后将其删除:

Private Sub CommandApply_Click()

Dim i As Long
Dim n As Long
Dim col As New Collection
Dim itm As Variant
Dim rng As Range

' First, collect the row numbers corresponding to the selected items
' We work from last to first
n = Me.ListBox1.ListCount
For i = n - 1 To 0 Step -1
    If Not Me.ListBox1.Selected(i) Then
        If rng Is Nothing then 
           Set rng = Worksheets("Sheet1").Range("A" & i + 1)
        Else
           Set rng = Union(rng, Worksheets("Sheet1").Range("A" & i + 1))
        End If
    End If
Next i

' Then delete the rows
If not rng Is Nothing then rng.Entirerow.delete
 blnCancel = False
   Me.Hide
End Sub
于 2014-07-29T15:05:19.077 回答