excel 如何用最快的方法删除过滤后的行?

wpx232ag  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(275)

我有一个30k行和15列的数据集。
我在列“O”上设置了自动过滤器,以选择包含字符串“x”的单元格并删除所有这些行。
代码需要很多时间来完成(约14秒)在一个非常强大的个人电脑。
我的代码是否经过了良好的规划,或者是否有更快的方法来删除这些筛选过的行?
提前,感谢任何有用的意见和答案。

Sub Macro1()

   Dim ws As Worksheet, rng As Range, lastR As Long, lastC As Long
   
   Set ws = ActiveSheet
    lastR = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row                      'Last Row on column 1
     lastC = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column             'Last Column on Row 1
     
    Set rng = ws.Range(ws.Cells(1, 1), ws.Cells(lastR, lastC))

    ws.Rows("1:1").AutoFilter
    rng.AutoFilter Field:=15, Criteria1:="x"
    
    Intersect(ws.Cells, rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow).Delete
    
End Sub
vmdwslir

vmdwslir1#

正如Joe所说,对数据进行排序可能会有所帮助。(别忘了在代码末尾打开它们)。而且,使用数组比直接使用工作表要快得多。不过,必须注意数据是否是静态的(即,不依赖于可能被改变的其余数据)。
我写了一段简单的代码来测试使用数组会有多快(或多慢)。

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Dim sh As Worksheet
Dim rng As Range
Dim n_rows As Long
Dim n_cols As Integer
Dim r_pointer As Long
Dim arr_in() As Variant
Dim arr_out() As Variant
Dim r As Long
Dim c As Integer

Const idx_init As Integer = 1
Const c_target As Integer = 15
Const s_cmp As String = "x"

n_rows = 30000
n_cols = 15

Set sh = Sheet1
Set rng = sh.Range("A1").Resize(n_rows, n_cols)

ReDim arr_in(idx_init To n_rows, idx_init To n_cols)
ReDim arr_out(idx_init To n_rows, idx_init To n_cols)

arr_in = rng.Value
r_pointer = 0
For r = n_rows To idx_init Step -1
  ' Adapt to case comparison mode required.
  If arr_in(r, c_target) <> x_cmp Then
    r_pointer = r_pointer + 1
    For c = idx_init To n_cols
      arr_out(r_pointer, c) = arr_in(r, c)
    Next c
  End If
Next r
rng.Value = arr_out

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

您的代码占用了1.58 sec
您的代码中包含ScreenUpdating和自动计算关闭了1.63 sec
我的代码采用了0.46 sec

相关问题