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
Doloop - The
Do-Untilloop - The
For NextloopForandFor Eachloops can both be used to iterate through collections and arrays. Only theForloop can be used to iterate through a range of specified values, for example,1to10. Only theForloop 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
LoopSampleSub procedure:Sub LoopSample() Range("A1").Select Do ...