Looping in Excel-VBA



Looping is a method in which a piece of code is executed number of times. Generally, a condition is checked is evaluated either at entry or at exit of the loop. The output determined whether to continue or exit the loop. Excel VBA has while ..wend, do..while, for..next statements to implement loop.

For Loop
For loop I used where one is certain about the number of times a loop is going to repeat.
ForVar=Initial_ValuetoFinal_Value
…..
…..
Next

 

While … Wend Loop 
It is employed when a loop has to repeat till a certain condition is True.
While [Condition]
 ….
 ….
Wend



Do..while..loop


This too works like while ..wend loop. It provides flexibility to evaluate condition at the entry or the exit of the loop. 


Do While [condition] 
…
...
Loop

 


Do
..
..
Loop While [condition]

 
 

Do…Until..loop
Looping instruction other than Do….Until….Loop exit the loop when the condition output is false. Do…Until loops exit the loop when the condition is true.

Do until [condition]
…
…
Loop

 
On executing the codes under every looping instruction, we will obtain following output.
 

At any point of time, if we wish to exit a for or do loop, we can implement the same using Exit instruction. Exit for & Exit do instruction helps one to prematurely exit a for and do..while loops.