我正在尝试遍历单元格区域并执行以下操作: 如果单元格具有背景色,则跳过。如果没有背景色,则删除整行。
我当前的代码有什么问题?
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
答案 0 :(得分:1)
使用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