In this section, we will learn For loop. For loop is an operation which repeats a same operation, so you don't need to write a long code if you can the loop. Here is the example of loop.
Sub LoopExample()
Dim StartNumber As Integer
Dim EndNumber As Integer
EndNumber = 5
For StartNumber = 1 To EndNumber
MsgBox StartNumber
Next StartNumber
End Sub
If you run this code, you will see "MsgBox StartNumber" is executed 5 times. This is the loop. Note that every time it is looped, the variable StartNumber is added 1. This is looped as long as the condition is satisfied. The condition is "To EndNumber" now and EndNumber is 5 here, so this is executed until the StartNumber becomes 5.
If you want to don't want to add any number to StartNumber every time it is looped, write "Step 0" as follows:
For StartNumber = 1 To EndNumber Step 0
MsgBox StartNumber
Next StartNumber
It executes the loop without adding any number. The problem is the condition for stopping the loop is never satisfied because StartNumber never become 5 if you don't add any number to StartNumber. If you want to stop this infinite loop after mistakenly executing it, press "control" and "pause break" on your keyboard.
If you want to add 2 to StartNumber every time it is looped, write "Step 2" in the same way.
Negative number is possible, too. If you write "Step -1", it decreases the StartNumber ever time it is looped.
Note that you must initialize the StartNumber in the for loop statement.
For StartNumber = 1 To EndNumber Step 0
MsgBox StartNumber
Next StartNumber
Even if you initialize the variable outside of the for loop statement, it makes an error when you compile the code. You must initialize the variable inside the for loop statement.
With for loop statement, we can add every number between 1 and 100. This operation would be very hard without using for loop statement.
Sub LoopExample()
Dim StartNumber As Integer
Dim EndNumber As Integer
Dim Result As Integer
EndNumber = 100
For StartNumber = 1 To EndNumber
Result = Result + StartNumber
Next StartNumber
MsgBox Result
End Sub
This add all numbers between 1 and 100.
If you want to see what is happening during the addition, we can change the code a little.
Sub LoopExample()
Dim StartNumber As Integer
Dim EndNumber As Integer
Dim Result As Integer
Dim counter As Integer
EndNumber = 100
For StartNumber = 1 To EndNumber
Result = Result + StartNumber
counter = counter + 1
Cells(counter, 1).Value = Result
Next StartNumber
End Sub
This writes the value of "Result" variable in the A column (ie, A1, A2, A3...) every time the loop is executed.