Do...Loop Statement

當條件為 True (真) 時重複執行 Do 與 Loop 陳述式之間的陳述式,或重複執行 Do 與 Loop 陳述式之間的陳述式,直至條件變為 True (真)。

語法

Do[{While | Until} condition = True]

陳述式區塊

[Exit Do]

陳述式區塊

Loop

Do

陳述式區塊

[Exit Do]

陳述式區塊

Loop[{While | Until} condition = True]

參數/元素:

Condition:比較表示式、數值型或字串型表示式,這些表示式的演算值為 True (真) 或 False (假)。

Statement block:當條件為 True (真) 時或直至條件變為 True (真) 之前要重複執行的陳述式。

只要條件為 True (真) 或直至某一條件為 True (真) 之前,Do...Loop 陳述式執行迴圈。用於結束迴圈的條件必須放在 DoLoop 陳述式之後。以下示例是一些有效的陳述式組合:

語法

Do While condition = True

...陳述式區塊

Loop

只要條件為 True (真),就重複執行 Do While 與 Loop 陳述式之間的陳述式區塊。

Do Until condition = True

...陳述式區塊

Loop

只要條件為 False (假),就重複執行 Do Until 與 Loop 陳述式之間的陳述式區塊。

Do

...陳述式區塊

Loop While condition = True

只要條件為 True (真),就重複執行 Do 與 Loop 陳述式之間的陳述式區塊。

Do

...陳述式區塊

Loop Until condition = True

重複執行 Do 與 Loop 陳述式之間的陳述式區塊,直至條件為 True (真)。

Exit Do 陳述式可用於無條件地結束迴圈。您可以在 Do...Loop 陳述式中的任意位置加入此陳述式。也可以使用 If...Then 結構定義一個結束條件,如下所示:

Do...

陳述式

If condition = True Then Exit Do

陳述式

Loop...

示例:

Sub ExampleDoLoop

Dim sFile As String

Dim sPath As String

    sPath = "c:\"

    sFile = Dir$( sPath ,22)

    If sFile <> "" Then

        Do

            MsgBox sFile

            sFile = Dir$

        Loop Until sFile = ""

    End If

End Sub