Loops

There are many varieties of these, but they are all basically the same in that they will repeat a line, or multiple lines, of code a set number times, or until a condition becomes True or False.

 

Excel VBA has 5 loops from which we can choose from. Depending on the situation they are to be used for would dictate the type of loop to choose. Some loops are best suited for looping while incrementing a number, while others are ideal for looping through anyone of Excels Objects. The most useful loops are For loop and the For Each loop.

 

Shown below are the 5 loops available to us in Excel VBA.

 

Do Do While Do Until For For Each

 

 

Don’t be Confuse they really are not that complicated – Let’s see theirs example formats.

 

Loop Name Formats of Loop Code
Do  

Do

<Code to repeat>

Loop While <Whatever>

 

Do While  

Do While <Whatever>

<Code to repeat>

Loop

 

Do Until  

Do Until <Whatever>

<Code to repeat>

Loop

 

For  

For <Variable>=<Any Number> To <Any Other Number>

<Code to repeat>

Next   <Variable>

 

For Each  

For Each <Object Variable> in <Object Collection>

<Code to repeat>

Next  <Object Variable>

 

 

Just remember, all they are doing is what you have instructed them to do (via code) either a set number of times or until a condition is met (True or False).