如果单元格具有背景颜色,则删除整行

Per*_*gas 2 excel vba excel-vba

我试图删除列D中的单元格具有背景颜色的所有行.我已经编写了下面的代码,但每次运行它时,它都会无限期地运行,直到它最终崩溃.这两个ws1lastrow2的明确界定(我提到它来清除的,为什么我的宏不运行这种可能性)

With ws1
    lastrow2 = ws1.Range("A" & Rows.Count).End(xlUp).Row

    For i = lastrow2 To 2 Step -1
        nodel = False

        If .Cells(i, "D").Interior.ColorIndex = 0 Then
            nodel = True
        End If

        If Not nodel Then
            .Rows(i).EntireRow.Delete
        End If
    Next i
End With
Run Code Online (Sandbox Code Playgroud)

Gar*_*ent 5

不要使用0:

Sub qwerty()
    Dim ws1 As Worksheet: Set ws1 = ActiveSheet
    Dim Nodel As Boolean
    With ws1
        lastrow2 = ws1.Range("A" & Rows.Count).End(xlUp).Row
        For i = lastrow2 To 2 Step -1
            Nodel = False
            If .Cells(i, "D").Interior.ColorIndex = -4142 Then
               Nodel = True
            End If
            If Not Nodel Then
                .Rows(i).EntireRow.Delete
            End If
        Next i
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

编辑#1:

如果要保留具有白色背景的单元格,请首先验证"white"对应于"colorindex = 2",然后在代码中使用2代替-4142.