vba 退出excel中的嵌套循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10536730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 16:06:39  来源:igfitidea点击:

exit a nested loop in excel

excelloopsexcel-vbavba

提问by franklin

i have a loop in a macro i'm writing of the following structure:

我在宏中有一个循环,我正在编写以下结构:

there are two worksheets in this book. raw data (hence the endpointData variable) and a G/L (General ledger) sheet (hence the endpointGL variable)

本书中有两个工作表。原始数据(因此是 endpointData 变量)和 G/L(总帐)表(因此是 endpointGL 变量)

there are three forloops in this function:

for这个函数中有三个循环:

(1) the first loop iterates through each record in the raw data file.
(2) the second loop iterates through the verified matches from REGEXP(a regular expression search) and
(3) the third loop goes through the G/L and finds a corresponding match and puts (using: PUT_DATA_RANGE) that data into the appropriate spot.

(1) 第一个循环遍历原始数据文件中的每条记录。
(2) 第二个循环遍历来自REGEXP(正则表达式搜索)的已验证匹配项,以及
(3) 第三个循环遍历 G/L 并找到相应的匹配项并将(使用:)PUT_DATA_RANGE该数据放入适当的位置。

Here's sort of what i'm getting at:

这是我的意思:

psuedocode:

伪代码:

For i = 2 To endpointData

    If SOME_TEST = True Then
        Set MATCHES = REGEXP.EXECUTE()
        For Each myMatch In MATCHES
            For j = 1 To endpointGL
                If myMatch.value = SOME_CONDITION Then
                    PUT_DATA_RANGE
                    Exit For
                ElseIf myMatch.value <> SOME_CONDITION Then
                    MsgBox ("there might be a problem")
                    ' EXIT BOTH LOOPS HERE

                    ' write handler code
            Next
            End If
        Next
    End If
Next i

now you'll notice that i have a few comments to myself. if the third loops finds no match in the G/L the code currently interrupts to notify the user. but that message box MsgBox("there might be a problem")is looped through along with the third loop. how do i get excel to exit BOTH loops and bring the FIRST for loop to the next availabe record in the raw data?

现在你会注意到我对自己有一些评论。如果第三个循环在 G/L 中找不到匹配项,则代码当前会中断以通知用户。但该消息框MsgBox("there might be a problem")与第三个循环一起循环。我如何让 excel 退出两个循环并将第一个 for 循环带到原始数据中的下一个可用记录?

by the way, i've tried exiting it with an Exit Forbut that doesn't seem to work exactly.

顺便说一句,我试过用 退出它,Exit For但这似乎并不完全有效。

采纳答案by vansimke

I see two options.

我看到两个选项。

1) Use a series of booleans to check if the outer loops should continue

1) 使用一系列布尔值来检查外循环是否应该继续

2) Use a goto statement to exit from the inner loop directly back to the main procedure

2)使用goto语句退出内循环直接回到主程序

In this situation, the goto might not be so bad since you aren't jumping to a completely different part of the code. Just document it well...

在这种情况下,goto 可能不会那么糟糕,因为您没有跳转到代码的完全不同的部分。把它记录好...