By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

While and For Loops in AutoIt

This Tutorial deals with While and For Loops in AutoIt.

Edited: 2013-08-01 10:33

This Tutorial has been replaced by Autoit Loops, and is no longer actively maintained.

This Tutorial deals with While and For Loops in AutoIt, and how the counter variable is incremented.

The while loop is perhaps the easiest to understand for beginners. You begin the loop with the while conditional statement, and end the loop with the WEnd keyword. Whatever goes between the two will be repeated over and over, until the script is either closed, or until the condition is met.

For loops can appear more complicated, since the counter variable will be increased in the statement itself.

The AutoIt while loop

To create a AutoIt while loop, we begin this script by declaring the counter variable, this will then be incremented inside the loop each time the loop is run. The incrementation is done inside the loop itself – by adding 1 to the counter variable. Example below:

$counter = 0
While $counter <= 5
    MsgBox(0, "Value of $counter is:", $counter)
    $counter = $counter + 1

The above while loop would run until the counter is equal to 5, or less than 5. If you remove the less than sign "<", and sets the counter to start at 5, the loop will only be run once.

The AutoIt for loop

For loops can appear a little more complicated than while loops, since the incrementation happens in the loop statement itself.

We first set the counter variable to 1 – $counter = 1 – next we write the end count – to 10 – this means that the counter will begin at 1, and end at 10. Each time the loop is executed, the counter is automatically increased by 1.

For $counter = 1 to 10
    MsgBox(0, "Counter: ", $counter)