简体   繁体   English

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

[英]Delete entire row, if a cell has a background color

I am trying to delete all the rows of which the cell in column D has a background color. 我正在尝试删除D列中的单元格具有背景色的所有行。 I have written the code below, but everytime I run it, it runs indefinitely until it eventually crashes. 我已经在下面编写了代码,但是每次运行它时,它都会无限期运行,直到最终崩溃。 Both ws1 and lastrow2 are well defined (I mention it to clear this possibility of why my macro is not running) 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

Don't use 0 : 不要使用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

EDIT#1: 编辑#1:

If you want to retain cells with a white background, first verify that "white" corresponds to "colorindex=2" and then use 2 in place of -4142 in the code. 如果要保留具有白色背景的单元格,请首先验证“白色”对应于“ colorindex = 2”,然后在代码中使用2代替-4142

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM