我有一个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
答案 0 :(得分:8)
使用Do ... Loop
和Exit 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