Excel VBA基于if语句删除行(加速)

时间:2016-10-24 13:50:21

标签: excel vba

我正在根据P列中的值删除行。 列P中的单元具有if语句:IF(K <10,0,1)

如果P列中的值为0,则需要删除该行。 我正在使用以下宏,它可以工作,但需要很长时间。 我想能够处理大约10000行。

如果我能就加快此代码提出一些建议,我将不胜感激。

[我曾尝试使用此if语句:IF(K <10,“”,1) 然后使用SpecialCells(XlCellTypeBlanks)删除行,但由于存在我假设的公式,因此单元格不会被解释为空白。 ]

 Sub RemoveBlankRows()

   Application.ScreenUpdating = False
    'PURPOSE: Deletes any row with 0 cells located inside P
    'Reference: www.TheSpreadsheetGuru.com

   Dim rng As Range
   Dim blankrng As Range
   Dim cell As Range

   'Store blank cells inside a variable
   'On Error GoTo NoBlanksFound
Set rng = Range("P2:P30000") '.SpecialCells(xlCellTypeBlanks)
'On Error GoTo 0

For Each cell In rng
If cell.Value = 0 Then
    cell.EntireRow.Delete
    'Value = ""
End If
Next

Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:0)

这会查找 0 并避免空白:

Sub RowKiller()
    Dim rKill As Range, r As Range, rng As Range

    Set rng = Range("P2:P30000")
    Set rKill = Nothing

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False

    For Each r In rng
        If r.Value = 0 And r.Value <> "" Then
            If rKill Is Nothing Then
                Set rKill = r
            Else
                Set rKill = Union(rKill, r)
            End If
        End If
    Next r

    If Not rKill Is Nothing Then rKill.EntireRow.Delete

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True

End Sub

这只是演示代码。定制它以满足您的需求。