更有效的删除行的方式

我有一些代码可以删除不在指定行号列表中的行。 它的function如预期。

For lRow = numRowsInBBS To 1 Step -1 lMatch = 0 On Error Resume Next lMatch = Application.Match(lRow, ws.Range("AE4:AE" & numRows).Value, 0&) On Error GoTo 0 If Not CBool(lMatch) Then wsImport.Cells(lRow, 1).EntireRow.Delete End If Next End Sub 

但是,这需要花费大量的时间。 要在150行上做到这一点需要几分钟的处理。 我有可能是1000行的文件。

基本上我想删除指定表中的所有行,除了在AE4:AE??指定的行号AE4:AE?? (这是由numRows计算)在不同的工作表上。

数据范围不连续, AE4:AE?? 可以列出数字3,4,5,33,66,101,110作为行保留。 所有其他行将被删除。

有没有更好的方法来实现我的目标?

我听说自动filter要快得多,但是看不到我在这里如何应用它,因为我没有匹配string或单元格中的任何内容,只是行号。

编辑:根据build议,我已经尝试了自动过滤的方式:

 Dim rowsToKeep() As Variant: rowsToKeep = ws.Range("AE4:AE" & numRows) Dim allRows As Range: Set allRows = Range("ZZ1:ZZ" & numRowsInBBS) With wsImport .Range(allRows.Address).Formula = "=row()" .Range(allRows.Address).AutoFilter Field:=1, Criteria1:=rowsToKeep, Operator:=xlFilterValues .Range(allRows.Address).SpecialCells(xlCellTypeVisible).EntireRow.Delete .Range(allRows.Address).AutoFilter Field:=1 End With 

我正在尝试:设置AE4:AE??范围内的数据AE4:AE?? 作为数组的数据 – 然后使用ZZ作为包含行号的帮助列 – 然后过滤掉我想保留的行 – 然后删除所有可见的行 – 然后显示被过滤的行

但是,filter隐藏了一切,这暗示了rowsToKeep有什么问题,并且是AE4:AE?? 在另一张纸上确实包含值。

试试这个( 未经testing

删除循环中的行将总是比较慢。 下面的代码所做的是将需要删除的行存储在一个范围对象中,然后在一次循环结束时删除它们。

 Dim delRng As Range For lRow = 1 To numRowsInBBS On Error Resume Next lMatch = Application.Match(lRow, ws.Range("AE4:AE" & numRows).Value, 0&) On Error GoTo 0 If Not CBool(lMatch) Then If delRng Is Nothing Then Set delRng = wsImport.Rows(lRow) Else Set delRng = Union(delRng, wsImport.Rows(lRow)) End If End If Next If Not delRng Is Nothing Then delRng.Delete 

使用CountIf未testing

 Dim delRng As Range For lrow = 1 To numRowsInBBS If Application.WorksheetFunction.CountIf(ws.Range("AE4:AE" & numRows), lrow) > 0 Then If delRng Is Nothing Then Set delRng = wsImport.Rows(lrow) Else Set delRng = Union(delRng, wsImport.Rows(lrow)) End If End If Next If Not delRng Is Nothing Then delRng.Delete