根据单元格颜色excel vba删除行

时间:2015-03-11 14:04:37

标签: excel vba rows

我正在尝试根据单元格颜色删除行。我遇到的问题是我写的代码保持“跳过行”:

 For i = 2 To lastRow
'MsgBox (Cells(i, 1) & " " & Cells(i, 1).Interior.ColorIndex)
    If Worksheets("Export Worksheet").Cells(i, 1).Interior.ColorIndex <> "4" Then
       'MsgBox ("Row " & i & " will be deleted")
       Rows(i).EntireRow.Delete
       'MsgBox ("i is currently " & i)
       i = i + 1
    'MsgBox ("i is now " & i)
    End If

Next i

有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:1)

删除行时应该向后循环。

 For i = lastRow to 2 Step -1 'Step --1 tells VBA to loop in reverse
'MsgBox (Cells(i, 1) & " " & Cells(i, 1).Interior.ColorIndex)
    If Worksheets("Export Worksheet").Cells(i, 1).Interior.ColorIndex <> "4" Then
       'MsgBox ("Row " & i & " will be deleted")
       Rows(i).EntireRow.Delete
       'MsgBox ("i is currently " & i)
       i = i + 1
    'MsgBox ("i is now " & i)
    End If

Next i