代码不会删除每个非数字行

时间:2015-11-17 21:26:26

标签: excel excel-vba vba

我在这里有这个代码,它通过一列数字查找,用数字为单元格着色并删除单元格及其对应的行,如果它是非数字条目(单元格用“ - ”填充)。它删除了一些非数字行但不是全部。

Dim wbI As Workbook, wbO As Workbook
    Dim wsI As Worksheet, wsO As Worksheet
    Dim iCounter As Long
    Dim iCounter1 As Long
    Dim iCounter2 As Long
    Dim lrow As Long, rw As Long
    Dim OutLookApp As Object
    Dim OutLookMailItem As Object
    Dim MailDest As String
    Dim subj As String
    Dim bod As String
    Dim lastrow As Long
    Dim lastrow1 As Long

 lastrow = wsI.Cells(Rows.Count, 4).End(xlUp).Row
lastrow1 = wsO.Cells(Rows.Count, 4).End(xlUp).Row

 With wsO
        For iCounter1 = 2 To lastrow
        If wsO.Cells(iCounter1, 9) > 120 Then

        wsO.Cells(iCounter1, 9).Interior.Color = RGB(255, 101, 101)

        ElseIf wsO.Cells(iCounter1, 9) > 0 And wsO.Cells(iCounter1, 9) < 120 Then

        wsO.Cells(iCounter1, 9).Interior.Color = RGB(169, 208, 142)

        End If
        Next iCounter1

        With wsO
        For iCounter2 = 2 To lastrow

         If Not IsNumeric(Cells(iCounter2, 9)) Then
         wsO.Cells(iCounter2, 9).EntireRow.Delete
         End If

        Next iCounter2


        Rows("2:200").RowHeight = 30
        End With
        End With

1 个答案:

答案 0 :(得分:3)

您的代码似乎有两个问题。跳过一些应删除的行的主要问题可以通过从底部循环到顶部来清除。如果没有以这种方式工作,可能意味着在删除行之后跳过一行,行重新编号,然后递增到下一行。

有一个次要问题,您已经实现了With ... End With statement引用要处理的工作表,然后在引用单元格/范围/行时重复工作表引用或完全丢弃它。

With wsO
    For iCounter1 = 2 To LastRow
        If .Cells(iCounter1, 9) > 120 Then
            .Cells(iCounter1, 9).Interior.Color = RGB(255, 101, 101)
        ElseIf .Cells(iCounter1, 9) > 0 And .Cells(iCounter1, 9) < 120 Then
            .Cells(iCounter1, 9).Interior.Color = RGB(169, 208, 142)
        End If
    Next iCounter1

    'this is the primary change
    'loop from the bottom to the top when deleting rows
    For iCounter2 = LastRow To 2 Step -1
        If Not IsNumeric(.Cells(iCounter2, 9)) Then
            .Cells(iCounter2, 9).EntireRow.Delete
        End If
    Next iCounter2

    .Rows("2:200").RowHeight = 30
End With

请注意,Cells变为.CellsRows变为.Rows。句点(aka .句号`)前缀将每个单元格/范围/行与With ... End With块中引用的父工作表相关联。

¹感谢Scott Craner注意到评论中从下到上的方法。