excel - 代码不删除每个非数字行

标签 excel 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

最佳答案

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

还有一个次要问题,您已实现 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。句点(又名 .句号`)前缀将每个单元格/范围/行与 With ... End With block 中引用的父工作表相关联。


1 感谢Scott Craner用于注释注释中从下到上的方法。

关于excel - 代码不删除每个非数字行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33767306/

相关文章:

python - 将结果写入 Excel

JAVA Excel POI API : formulas not updated

java - 如何使用 java Apache POI 库从 XLSX 文件的特定单元格中获取值

excel - 多维数组(1 到 #) - Lbound 显示为 0,而不是 1?

excel - 如何使用 for/next VBA 调用 sub

excel - 计色后表现不佳

vba - If 语句 VBA Excel 2010

excel - 如何在excel vba中单击切片器中的值时运行宏

vba - Worksheet_Change 事件中的目标范围不正确

vba - 使用 VBA 从 Excel 2013 中的日期中提取星期数