Excel VBA删除许多不同的行

时间:2019-03-05 03:21:44

标签: excel vba

我正在使用Excel 365,并试图删除许多差异行并具有一些可运行的代码,但是效率很低。与手动过滤列,突出显示行并删除相比,从大约2000行中删除500行需要很长时间,因此我想一次删除所有需要删除的行,但没有成功。我的工作代码是:

' When cell contains TRUE, erase that row
For i = LastRow To firstDataRow Step -1
    If Cells(i, eraseCol).Value = True Then
        sheetdata.Rows(i).Delete
        LastRow = LastRow - 1
    End If
Next

我想做的事不起作用:

For i = LastRow To firstDataRow Step -1
    ' collect all rows to be deleted in range r
    If Cells(i, eraseCol).Value = True Then
        r = Union(Rows(i), r)
    End If
Next
r.Delete

有什么主意如何让r中的所有行都删除并立即执行?还是有更好的方法?

2 个答案:

答案 0 :(得分:2)

' collect rows to be deleted into range r

' Alternate loop construct using iterator (partial code - diff only)
' Dim i as Range
' For Each i in <column range> ' i.e. <EraseCol>2:<EraseCol>10000
'     If i.value Then
'         If r Is Nothing Then
'             Set r = i
'         Else
'             Set r = Union(r, i)
'         End If
'     End If
' Next i

' No need to step backward, this will only scroll up one time.
For i = firstDataRow to LastRow
    If Cells(i, eraseCol).Value Then
        If r Is Nothing Then
            Set r = Rows(i)
        Else
            Set r = Union(r, Rows(i))
        End If
    End If
Next i
r.EntireRow.Delete ' NO UNDO - wipes undo buffer

答案 1 :(得分:0)

您很近。试一试:

        mutate(fittest)  # Mutate fittest in place
        population.append(fittest[:])  # Append copy of most recently updated fittest

N.B -由于您只收集某个范围内的单元格,因此可以根据需要循环播放;但是向后循环仍然可以工作