VBA Loops: For, Do While, Do Until
Master all VBA loop types to automate repetitive tasks efficiently
Quick Reference
For Next: Loop a specific number of times
For Each: Loop through collection items
Do While: Loop while condition is true
Do Until: Loop until condition becomes true
Understanding VBA Loops
Loops allow you to repeat code multiple times without writing it repeatedly. VBA offers several loop types for different situations.
For Loops
- ✓ Known number of iterations
- ✓ Counter-based
- ✓ Best for: Arrays, ranges, sequences
Do Loops
- ✓ Unknown number of iterations
- ✓ Condition-based
- ✓ Best for: Until criteria met
For...Next Loop
Use when you know exactly how many times to repeat code.
Basic Syntax:
Example 1: Loop 1 to 10
Example 2: Loop Through Rows
Fills A1:A100 with "Row 1", "Row 2", etc.
Example 3: Using Step (Count by 2s)
Example 4: Countdown (Negative Step)
Pro Tip: Use Long instead of Integer for large row counts (>32,767).
For Each...Next Loop
Iterate through all items in a collection without counting.
Basic Syntax:
Example 1: Loop Through Range
Example 2: Loop Through Worksheets
Example 3: Loop Through Array
When to use: For Each is cleaner when you need to process every item and don't need the index number.
Do While Loop
Repeats code while a condition is true. Checks condition before each iteration.
Basic Syntax:
Example 1: Find Last Row
Example 2: Loop Until Value Found
Example 3: User Input Loop
Warning: Always include an exit condition to prevent infinite loops!
Do Until Loop
Repeats code until a condition becomes true. Opposite logic of Do While.
Basic Syntax:
Example 1: Fill Until Blank
Example 2: Import Until End of File
Do While vs Do Until:
Do While:
Loop continues WHILE condition is True
Do While x < 10Do Until:
Loop continues UNTIL condition is True
Do Until x = 10Loop Variations
Do...Loop While (Check at End)
Condition checked AFTER first iteration. Guarantees at least one execution.
Do...Loop Until (Check at End)
Similar to Do While, but with Until logic at the end.
Nested Loops
Place one loop inside another to work with multi-dimensional data.
Example: Fill 2D Grid
Creates a 10x5 multiplication table
Important: Inner loop completes all iterations for each single iteration of outer loop.
Loop Control Statements
Exit For / Exit Do
Immediately exit loop when condition met.
Continue (VBA Workaround)
VBA doesn't have Continue, but use If to skip iterations:
Loop Best Practices
Application.ScreenUpdating = False before loopsCommon Loop Mistakes
❌ Infinite Loop
Always modify the loop variable or condition inside the loop.
❌ Modifying Collection While Looping
Loop backwards or use For Next when deleting items.
❌ Inefficient Worksheet Access
Use arrays for large data operations instead of cell-by-cell access.