即使不满足IF-THEN条件,也继续执行FOR-NEXT循环

时间:2019-03-18 19:58:04

标签: excel vba loops if-statement

只要满足IF-THEN条件,我当前的FOR-NEXT循环就可以工作。但是,一旦不满足IF-THEN条件,循环就会停止。我希望循环继续进行,即使不满足IF-THEN条件。我想检查表中的所有行。 VBA新手。任何帮助表示赞赏。

Dim EngHisTable As ListObject

Set EngHisTable = Sheets("Historic").ListObjects("Table2")

Dim WeekCode As String
WeekCode = Sheets("Weekly").Range("B5").Value

For x = EngHisTable.ListRows.Count To 1 Step -1

    If EngHisTable.ListRows(EngHisTable.ListRows.Count).Range(, 15) = WeekCode Then
        EngHisTable.ListRows(EngHisTable.ListRows.Count).Delete
    End If

Next x

1 个答案:

答案 0 :(得分:0)

您实际上并没有在循环中使用x。如果要这样做,它将看起来像这样:

For x = EngHisTable.ListRows.Count To 1 Step -1
    If EngHisTable.ListRows(x).Range(, 15) = WeekCode Then
        EngHisTable.ListRows(x).Delete
    End If
Next x

或者,您可以一次过滤并删除与WeekCode相对应的所有行,而不必逐行循环:

Sub MyDelete()
    Dim EngHisTable As ListObject
    Set EngHisTable = Sheets("Historic").ListObjects("Table2")

    Dim WeekCode As String
    WeekCode = Sheets("Weekly").Range("B5").Value

    With EngHisTable
        .Range.AutoFilter Field:=15, Criteria1:=WeekCode

        On Error Resume Next
        Dim rngToDelete As Range
        Set rngToDelete = .DataBodyRange.SpecialCells(xlCellTypeVisible)
        On Error GoTo 0

        .AutoFilter.ShowAllData
        If Not rngToDelete Is Nothing Then rngToDelete.Delete xlShiftUp
    End With
End Sub