- Using Loops in VBA can be helpful when you want to perform a repetitive task.
- You can also use a loop inside another loop (nesting).
- Make sure to be cautious while creating an infinite loop.
What is a LOOP in VBA?
In VBA, a LOOP is a structure that can repeat a statement. In simple words, a loop can perform an activity or multiple activities and go back to the starting to do it again for a number of times or until a condition is met. This cycle of execution of a loop is called an iteration.
Types of LOOPS in VBA
In VBA, there are six different types of loops that you can use but you can also describe them in two basic categories.
- For Next: To use FOR NEXT LOOP you need to define a number as a counter for the loop run number of times. If you want to run a loop for 10 times then you need to define that value for the counter.
- For Each: With FOR EACH, you can loop through all the objects in a collection of objects. As every collection has a defined number of objects that makes it a fixed loop.
- Do While Loop: It tests a condition and then keeps performing the activity while that condition is TRUE. In simple words, it will first test a condition and only execute the statement if that condition is met.
- Do Loop While: It works same as “Do While”, but it performs one iteration of the activity first and then test the condition and if that condition is TRUE then keeps performing that activity.
- Do Until Loop: It tests a condition and then keeps executing the statement you have defined until that condition is FALSE and the moment that condition turns TRUE it will stop. Basically, it’s an opposite of “Do While”.
- Do Loop Until: it works same as “Do Until” but it performs one iteration of the activity first and then test the condition and if that condition is FALSE then keeps performing that activity.