如何在Excel VBA中退出多个for循环?

时间:2015-03-06 19:10:29

标签: excel excel-vba vbscript vba

代码就像

'first for loop
for I = 1 to 5 
    do sth
    'second for loop
    for j = 2 to 7
        do sth
        'third for loop
        for m = 2 to 43
            if [condition] then 
               exit 2nd and 3rd loop and continue on next I ?????
            end if
        next
    next
next

我写了两个“退出”,但它没有帮助。它只退出第3个循环并继续下一个j。

3 个答案:

答案 0 :(得分:7)

如果在循环中嵌套一个标志,则可以在循环第二个循环之前放置一个if语句。如果该标志为真,那么您也退出第二个循环。

'first for loop
for I = 1 to 5 
    do sth
    'second for loop
    for j = 2 to 7
        do sth
        'third for loop
        for m = 2 to 43
            if [condition] then 
               flg = True
               Exit for
            end if
        next
    If flg = True then Exit For
    next
next

答案 1 :(得分:2)

虚拟Do...Loop包含:

' first for loop
For i = 1 To 5
    ' do sth
    ' dummy do loop, won't repeat, just creating a block to exit from
    Do
        ' second for loop
        For j = 2 To 7
            ' do sth
            ' third for loop
            For m = 2 To 43
                If [Condition] Then
                   ' exit 2nd and 3rd loop and continue on next i
                   Exit Do
                End If
            Next
        Next
    Loop Until True ' never repeats
    ' continue within 1st for loop
Next

答案 2 :(得分:1)

    For a = 1 To maxRows
        If Exam1Grade(a) > 99 Then
        For b = 1 To maxRows
            If Exam2Grade(b) > 99 Then
            For c = 1 To maxRows
                If Exam3Grade(c) >= 100 Then
                    MsgBox ("Stop looking through the 3rd exam, you have just found the perfect score")
                    GoTo ThisPoint 'Exit All For Loops
                ElseIf c = maxRows Then 'Restart At A
                    GoTo NextA
                End If
            Next c
            End If
        Next b
        End If
NextA:
    Next a
ThisPoint:

GoTo语句可以作为中断