Using loops
In this final recipe of this chapter, we will show you how to use loops.
Loops are used to automatically repeat a set of statements until a condition is met. There are different types of loops that can be used in VBA:
- The
Do
loop - The
Do-Until
loop - The
For Next
loopFor
andFor Each
loops can both be used to iterate through collections and arrays. Only theFor
loop can be used to iterate through a range of specified values, for example,1
to10
. Only theFor
loop can be used to replace items of an iterated collection or array. - Looping through a collection of objects
Getting ready
With ProgramFlow.xlsm
still open on Sheet1, press Alt + F11 to switch to the VBA Editor With that open, insert a new module.
How to do it…
The first loop under discussion is the Do
loop:
- Type the following code into the
LoopSample
Sub procedure:Sub LoopSample() Range("A1").Select Do ...