在 VBA/VBS 中退出 while 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32797367/
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-08 09:59:27  来源:igfitidea点击:

Exit a while loop in VBA/VBS

excelvbaexcel-vbavbscript

提问by bigbryan

I have an Excel VBA program that loops through each row of data in a data sheet.

我有一个 Excel VBA 程序,它循环遍历数据表中的每一行数据。

My goal is to exit the while loop once boolean bFoundis set as True.

我的目标是一旦布尔值bFound设置为True.

I think my condition "Or bFound=True" might be incorrect.

我认为我的条件“Or bFound=True”可能不正确。

bFound = False
While Sheets("Data").Cells(iRow, 1) <> "" Or bFound = True

    If Sheets("Data").Cells(iRow, 11) = Sheets("Data2").Cells(iRow, 1) Then
        bFound = True
    End If

    iRow = iRow + 1
Wend
'exit loop after the boolean=true

回答by omegastripes

Use Do ... Loopand Exit Do

使用Do ... LoopExit Do

bFound = False
Do While Sheets("Data").Cells(iRow, 1) <> ""
    bFound = Sheets("Data").Cells(iRow, 11) = Sheets("Data2").Cells(iRow, 1)
    If bFound Then Exit Do
    iRow = iRow + 1
Loop

回答by Selfish

Flip the logic around, I expect this will work for you:

翻转逻辑,我希望这对你有用:

bFound = False
While Sheets("Data").Cells(iRow, 1) <> "" And bFound = False

    If Sheets("Data").Cells(iRow, 11) = Sheets("Data2").Cells(iRow, 1) Then
        bFound = True
    End If

    iRow = iRow + 1
Wend

Explanation:

解释:

While Sheets("Data").Cells(iRow, 1) <> "" And bFound = False

will allow the loop to carry on only while we still have data to process AND we still haven't changed bFound, which has initial value of False.

将允许循环仅在我们还有数据要处理并且我们仍然没有改变时继续进行bFound,它的初始值为False



Another option is to use the breakable form of While in VBS:

另一种选择是在 VBS 中使用 While 的可破坏形式:

Do While Sheets("Data").Cells(iRow, 1) <> ""

    If Sheets("Data").Cells(iRow, 11) = Sheets("Data2").Cells(iRow, 1) Then Exit Do

    iRow = iRow + 1

Loop