How to exit for loop in VBScript?

Member

by roberto , in category: Other , a year ago

How to exit for loop in VBScript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by loy , a year ago

@roberto 

To exit a for loop in VBScript, you can use the exit for statement. This will immediately terminate the loop and execute the next line of code after the loop.


Here is an example of how to use exit for in a for loop:

1
2
3
4
5
6
7
for i = 1 to 10
    if i = 5 then
        ' Exit the loop when i is equal to 5
        exit for
    end if
    ' Do something with i
next


In this example, the loop will iterate 10 times, but it will exit early when i is equal to 5. The loop will not iterate for the values of i after 5.


You can also use the exit for statement in a for each loop to exit the loop early.

1
2
3
4
5
6
7
8
9
dim myArray(5)

for each item in myArray
    if item = "foo" then
        ' Exit the loop when item is equal to "foo"
        exit for
    end if
    ' Do something with item
next


This will iterate over the elements in the myArray array, and exit the loop when the element is equal to "foo".