在VBA / VBS中退出while循环

时间:2015-09-26 12:49:56

标签: excel vba excel-vba vbscript

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

我的目标是在布尔bFound设置为True后退出while循环。

我认为我的情况"或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

2 个答案:

答案 0 :(得分:8)

使用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

答案 1 :(得分:5)

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

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

说明:

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

只允许在我们仍有数据要处理的情况下继续循环,我们仍然没有更改bFound,其初始值为False

另一个选择是在VBS中使用Break的可分解形式:

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