Export (0) Print
Expand All

Exiting a Loop

Microsoft® Windows® 2000 Scripting Guide

After you have entered a Do loop, VBScript will, by default, process each line of code within that loop. In most cases, that is exactly what you want it to do. However, there might be times when you want to exit a loop immediately, without running every line of code. In that event, you can use the Exit Do statement to immediately stop processing of the loop.

For example, the following script has been designed to cause an error (dividing 5 by 0). The loop condition states, "Run this loop until an Err occurs" (Err <> 0). That might lead you to believe that the loop will stop as soon as the script attempts to divide 5 by 0.



On Error Resume Next
Do Until Err <> 0
    X = 5/0
    Wscript.Echo "The result of the equation is " & X & "."
Loop

When you run the script, however, you see the dialog box shown in Figure 2.17.

Figure 2.17 Erroneous Message Box

sas_vbs_18s

Why? When the script encountered the divide by 0 error, it did not exit the loop, even though the loop condition specified, "Run this loop until an error occurs." Instead, it continued processing the remaining statements in the loop. This is because the loop condition, in this example, is tested only before the loop is running. As a result, the dialog box echoes the message, "The result of the equation is " and the result of the equation, which happens to be Null. After processing this statement, the script loops around, checks the error condition, and then exits the loop.

If you need to stop a loop before the loop actually completes, use the Exit Do statement. In the following script the error condition is checked within the loop itself. If an error has occurred, an error message is displayed, and the Exit Do command is used to stop the loop. If no error has occurred, the result of the equation is displayed.



On Error Resume Next
Do Until Err <> 0
    X = 5/0
    If Err <> 0 Then
        Wscript.Echo "An error has occurred."
        Exit Do
    End If
        Wscript.Echo "The result of the equation is " & X & "."
Loop

When the preceding script runs, the message box shown in Figure 2.18 appears. As you can see, the script stopped the loop before processing the statement that would have displayed the equation result.

Figure 2.18 Message Box Indicating That an Error Has Occurred

sas_vbs_19s
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft