2015-09-26 249 views
4

我有一個Excel VBA程序,循環訪問數據表中的每行數據。在VBA/VBS中退出while循環

我的目標是一旦布爾型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 
+1

更換**或**與**而* * –

+0

[在VBS/VBA中退出while循環]的可能重複(http://stackoverflow.com/questions/1271949/exit-a-while-loop-in-vbs-vba) – Selfish

回答

6

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

真棒。謝謝。 – bigbryan

+0

@bigbryan,請注意,在循環之外'iRow'指向退出條件已經匹配的行,但不會按照它在代碼中預期的那樣排到下一行。 – omegastripes

+0

注意。謝謝@omegastripes。 – bigbryan

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:

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