For Loop留下不需要的行

时间:2018-03-14 15:03:12

标签: excel-vba vba excel

...因为该行仅被评估一次而下一行被调用以进行评估。但下一行现在是前一行。我如何解释这个?

For i = 5 To Range("A" & "65536").End(xlUp).Row Step 1
If Application.WorksheetFunction.CountIf(Range("A" & i), "#N/A") = 1 Then
Range("A" & i).EntireRow.Delete
End If
Next i

2 个答案:

答案 0 :(得分:2)

您可以使用Union一次删除所有行。像这样:

Sub test()
    Dim i As Long
    Dim deleteRange As Range

    For i = 5 To Range("A" & "65536").End(xlUp).Row Step 1
        If Application.WorksheetFunction.CountIf(Range("A" & i), "#N/A") = 1 Then
            If deleteRange Is Nothing Then
                Set deleteRange = Range("A" & i).EntireRow
            Else: Set deleteRange = Union(deleteRange, Range("A" & i).EntireRow)
            End If
        End If
    Next i

    deleteRange.Delete
End Sub

答案 1 :(得分:1)

向后循环(并使用Rows.Count而不是硬编码65536),因为新版本的Excel容量超过一百万行。

For i = Range("A" & Rows.Count).End(xlUp).Row To 5 Step -1
    If Application.WorksheetFunction.CountIf(Range("A" & i), "#N/A") = 1 Then
        Range("A" & i).EntireRow.Delete
    End If
Next i