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

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

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语句来引用工作表,然后在引用单元格/范围/行时重复工作表引用,或者完全放弃它。

 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在评论中注意到从下到上的方法。