For-Next loop

Loops are structures that are used if we want to repeatedly execute given program code. The easiest to understand and probably most often used is the For-Next Loop. It is used when we know exactly how many times we want to repeat a particular action. First, the initial and the end value are set; we can also set the optional Step value for which counter is being incremented. Further we enter the programme code and in the end Next statement and a counter name.

The For-Next loop syntax is:

For <counter> [As <data type>] = <start value> To <end value> [Step <step value> ]
[PROGRAMME STATEMENTS]
[Continue For]
[PROGRAMME STATEMENTS]
[Exit For]
[PROGRAMME STATEMENTS]
Next [<counter>] 

For example, if we want 5 times to show the sentence “I like Excel” we need to write the following code:

Dim i As Integer
For i = 1 To 5
    MsgBox “I like Excel”
Next i

If we wanted to show odd numbers less than 10 we would write the following code:

Dim i As Integer
For i = 1 To 10 Step 2
    MsgBox i
Next i