Excel 如果单元格未高亮显示,则删除整行

Excel 如果单元格未高亮显示,则删除整行,excel,vba,Excel,Vba,我正在尝试通过一系列单元格并执行以下操作: 如果单元格有背景色,则跳过。如果没有背景色,则删除整行 我当前的代码有什么问题 Sub RemoveRowsThatAreNotHighlighted123() Dim cell As Range Dim rng As Range Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Set rng

我正在尝试通过一系列单元格并执行以下操作: 如果单元格有背景色,则跳过。如果没有背景色,则删除整行

我当前的代码有什么问题

Sub RemoveRowsThatAreNotHighlighted123()

    Dim cell As Range
    Dim rng As Range

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Set rng = ThisWorkbook.Worksheets("Main").Range("A2:L" & ThisWorkbook.Worksheets("Main").Range("C2").End(xlDown).Row)

    For Each cell In rng
        If cell.Interior.ColorIndex = 0 Then cell.EntireRow.Delete
    Next

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub

使用
xlColorIndexNone
代替
0

此外,在删除行时,建议始终向后循环,如下所示:

Sub RemoveRowsThatAreNotHighlighted123()
    Dim iRow As Long

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    With ThisWorkbook.Worksheets("Main") ' reference your workbook and worksheet
        With .Range("A2:L" & .Range("C2").End(xlDown).Row) ' reference referenced worksheet range from A2 down to column C last not empty cell before first empty one
            For iRow = .Rows.Count To 1 Step -1 ' loop from referenced range last row backwards
                If .Rows(iRow).Interior.ColorIndex = -4142 Then .Rows(iRow).EntireRow.Delete ' if alll referenced range current row cells have no background then delete row
            Next
        End With
    End With
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub

隐马尔可夫模型。。出于某种原因,这会删除工作表上的所有数据