有条件地退出嵌套for循环 - VBA

时间:2014-03-11 09:53:11

标签: vba for-loop nested-if

我有以下问题。我有几个源文件要复制到我的摘要表中(列/行的顺序可以不同)。因此,我试图用h / v-lookup组合进行一些硬编码检查。代码如下:

For i = 2 To Row_number

    '''' 1150 ''''
    If (Cells(i, 42).Value = "1150") Then

        If (WB_1150 Is Nothing) Then
            Set WB_1150 = Workbooks.Open(directory & file_1150)

            For Each wb In Workbooks
                If (wb <> ThisWorkbook & wb <> WB_1150) Then
                    wb.Close savechanges = False
                End If
            Next wb
        End If

        bool_vlookup_result = IsError(Application.vlookup(ThisWorkbook.Sheets(sheet_name_swaption).Cells(i, 12), WB_1150.Sheets(1).range("V1:V" & Row_number), 1, False))

        If (bool_vlookup_result = True) Then
            ThisWorkbook.Activate
            Sheets(sheet_name_swaption).Activate
            Cells(i, 43).Value = "ERROR"
            Next i
        Else
            row_index_result = Application.Match(Cells(i, 2), WB_1150.Sheets(1).range("V1:V" & Row_number), 0)

            For j = 1 To 42

                If (Cells(row_index_result, j) = "") Then
                    Next j
                Else
                    bool_hlookup_result = IsError(Application.HLookup(ThisWorkbook.Sheets(sheet_name_swaption).Cells(i, j), WB_1150.Sheets(1).range(Cells(row_index_result, 1), Cells(row_index_result, 22)), 1, False))

                    If (bool_hlookup_result = True) Then
                        ThisWorkbook.Activate
                        Sheets(sheet_name_swaption).Activate
                        Cells(i, 43).Value = "ERROR"
                        Next i
                    End If

                End If

            Next j

            ThisWorkbook.Activate
            Sheets(sheet_name_swaption).Activate
            Cells(i, 43).Value = "OK"
        End If

    End If
    '''' End 1150 ''''

''' OTHER SOURCE FILES '''

Next i

我收到错误Next没有For,因为一旦我收到错误,我可以跳到下面的i / j。有什么建议可以解决/改善吗?我知道有几种方法可以进行这些检查,但这是我发现的最强大(也是最耗时)的工具。非常感谢提前。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

For i = 1 To 10
    If i = 3 Then GoTo Cont
    Debug.Print i
Cont:
Next i