Does your code need to execute the same action more than once? Instead of programming it multiple times, try writing it once and repeating it with a loop.

Key Takeaways

  • A VBA For loop repeats a block of code a set number of times, making it the most common loop for automating repetitive Excel tasks.
  • Excel VBA offers several loop types (For...Next, Do...Until, Do...While) and choosing the right one depends on whether you know the number of iterations in advance.
  • You can nest loops inside each other to process multi-dimensional ranges like rows and columns simultaneously.
  • Common loop mistakes like infinite loops and off-by-one errors are easy to prevent with a few best practices.

What Is a VBA For Loop?

VBA, or Visual Basic for Applications, is Excel's built-in programming language. It lets you write macros that automate repetitive tasks across your spreadsheets, from formatting cells to processing thousands of rows of data. A VBA For loop is one of the most fundamental control structures in VBA. It repeats a block of code a specified number of times, using a counter variable that increments with each pass.

Think of it this way: instead of manually editing 500 cells one at a time, a for loop VBA macro handles the entire operation in seconds. Whether you need to populate a column with calculated values, apply formatting across a range or cycle through a list of records, a VBA loop gives your code the ability to do the heavy lifting.

VBA offers several loop types beyond the For loop, and each one is suited to different situations. The next section compares them so you can choose the right structure for your task.

When to Use Each VBA Loop Type

Excel offers several different loop structures, depending on the conditions under which it should execute. Check out the table below to see how each loop works and an example of what it might look like as driving directions.

VBA Loop How It Works Real-Life Analogy Best Used When
For...Next Executes a certain number of times "Turn right three times, then stop." You know exactly how many times the code should repeat
Do...Until Executes until a condition is true, then stops "Keep going until you cross the railroad tracks, then turn left." You want the loop to stop when a specific condition is met
Do...While Executes while a condition is true and stops when it is no longer true "Keep going while the ditch runs alongside the road, then turn right." You want the loop to continue only as long as a condition remains true
For Each Iterates through every item in a collection "Stop at every house on the street and deliver a package." You need to process every object in a group such as each cell in a range or each worksheet in a workbook

Choosing the right loop type comes down to one question: do you know in advance how many times the code needs to run? If yes, a For...Next loop is usually the best choice. If no, a Do...While or Do...Until loop lets the data itself determine when to stop. And when you need to act on every item in a collection without tracking a counter, a For Each loop keeps your code clean and readable.

Read on for a walkthrough of each loop type with code examples you can adapt for your own Excel macros.

For Loop

To repeat a section of code a specific number of times, use a For...Next loop. The structure follows the pattern For [counter] = [start] To [end] ... Next [counter].

Fred Pryor Seminars_Excel Macro Loop 1A

This macro executes the "Cells(i,1).value = i" instruction with i = one. When it reaches the line "Next i," the macro increases the value of i to two and executes the "Cells" line again. It repeats a third time with i = three, and finally with i = four.

The result:

Do Until Loop

Sometimes you don't know how many times to execute a loop, but instead wish to run the loop until a certain condition is met. To do this, use a Do...Until loop.

Fred Pryor Seminars_Excel Macro Loop 1B

This code first checks whether the active cell is empty. If not, the code increments the value by one and moves the active cell selector down one row. Finally, it returns to the top of the loop and tests whether the new cell is empty, repeating the loop until it reaches an empty cell.

Beginning with these numbers, if you select cell B3 and begin the macro, it will produce:

Each cell value is increased by one, until the macro reaches cell B13, an empty cell, and stops.

Do While Loop

Similar to the Do . . . Until loop, the Do . . . While loop executes the code while a condition is true.

Fred Pryor Seminars_Excel Macro Loop 1C

The difference between Do . . . Until and Do . . . While is subtle, yet simple:

  • Do . . . Until executes as long as the condition is not true and stops when it becomes true, and
  • Do . . . While executes as long as the condition is true and stops when it becomes false.

Nested Loops

For even more power, try running a loop inside a loop. This example combines a For loop (to iterate through rows) with a Do...Until loop (to iterate through columns until a blank cell is found), allowing you to process a two-dimensional range.

This loops through the first 30 rows of the spreadsheet. On each row, it begins in column A and increments the cell value by one until it reaches a blank cell.

Fred Pryor Seminars_Excel Macro Loop 1D

Tips for Writing Efficient VBA Loops

Once your loops are working correctly, a few adjustments can make them run significantly faster. These tips are especially useful when your macro processes large datasets with hundreds or thousands of rows.

1. Turn Off Screen Updating

Add Application.ScreenUpdating = False before your loop and set it back to True after the loop finishes. This prevents Excel from refreshing the display on every iteration, which can dramatically reduce macro running time.

2. Set Calculation to Manual

Use Application.Calculation = xlCalculationManual before the loop and restore it with xlCalculationAutomatic afterward. This stops Excel from recalculating every formula each time a cell value changes inside the loop.

3. Use Specific Data Types

Declare your counter variables as Long instead of Variant. Specific data types use less memory and process faster, which adds up over thousands of iterations.

4. Read Data into an Array

Instead of reading and writing cell by cell, load your range into a VBA array, process the array in memory and write the results back to the range in a single operation. This approach can cut execution time from minutes to seconds on large datasets.

5. Avoid Select and Activate

Referencing cells directly with Cells(i, 1).Value is much faster than using Range("A1").Select followed by ActiveCell.Value. Every Select or Activate call forces Excel to update the interface, which slows your loop.

6. Move Static Operations Outside the Loop

If a calculation or variable assignment produces the same result on every iteration, move it above the loop. Only include operations inside the loop body that genuinely need to repeat.

Common VBA Loop Mistakes and How to Fix Them

Even experienced VBA users run into loop problems from time to time. Here are the most common mistakes and how to address them.

  • Infinite loops. A Do...While or Do...Until loop that never meets its exit condition will run forever and freeze Excel. If this happens, press Ctrl+Break (or Ctrl+Pause on some keyboards) to interrupt the macro. To prevent infinite loops, always verify that your loop body modifies the variable or condition being tested so the exit condition will eventually be met.
  • Off-by-one errors. A VBA For loop that starts at 0 instead of 1, or ends one row too early, can skip data or throw an error. Double-check your start and end values against the actual range of your data, remembering that Excel rows and columns are 1-based. 
  • Forgetting to advance the loop. In Do loops, if you forget to move the active cell or increment a counter variable, the loop tests the same condition repeatedly and never exits. Always include a line that advances the loop toward its exit condition, such as ActiveCell.Offset(1, 0).Select.
  • Modifying a collection while looping through it. Deleting rows while looping forward causes the loop to skip rows because the row numbers shift. When deleting rows in a loop, iterate backward (from the last row to the first) so deletions do not affect the rows you have not yet processed.

Where to Go from Here

Loops give your code the power to repeat actions. With the variety of loops available in Excel, your code can adapt to any conditions, even when you don't know ahead of time whether your code needs to run one time or a thousand.

In this article you walked through four loop structures: For...Next for a known number of iterations, Do...Until and Do...While for condition-based repetition and nested loops for processing multi-dimensional ranges. Combined with the performance tips and troubleshooting guidance above, you have a solid foundation for writing efficient, reliable Excel macro loop code.

Mastering VBA loops is a skill that pays off every time you open a spreadsheet. If you are ready to go deeper, Pryor Learning offers live virtual and In-Person seminars covering Excel VBA and other Microsoft Office skills. Explore Pryor Learning's Excel training courses for hands-on instruction with expert trainers who can help you build on what you have learned here.

Commonly Asked Questions

To create a loop macro in Excel, open the VBA Editor by pressing Alt+F11, insert a new module and write a Sub procedure containing a For...Next, Do...While or Do...Until loop structure. Define your loop's start and end conditions, add the code you want to repeat inside the loop body and run the macro to execute it. 

Press Ctrl+Break (or Ctrl+Pause on some keyboards) to interrupt a runaway macro, then click "End" in the dialog box to stop execution. To prevent infinite loops, always ensure your Do...While and Do...Until loops have a condition that will eventually be met and verify that your loop body modifies the variable being tested. 

A For...Next loop repeats code a set number of times using a numeric counter, while a For Each loop iterates through every item in a collection (such as each cell in a range or each worksheet in a workbook) without requiring you to know the total count. Use For...Next when you need a specific counter variable and For Each when you want to process every object in a group. 

At minimum, your Excel Gantt chart should include a task name, start date and duration for each task. You can add columns for task dependencies, assigned team members, completion percentage and status to make it more useful. The more structured your data table, the more dynamic and informative your chart will be. 

Yes, you can use a VBA For loop to iterate through a range by setting the counter to run from the first row to the last row (or column) of your data. For example, For i = 1 To 100 combined with Cells(i, 1).Value processes each cell in column A from row one to row 100. 

A nested loop is a loop placed inside another loop, allowing you to process data across two dimensions such as rows and columns. Use nested loops when you need to perform an action on every cell in a multi-row, multi-column range or when an inner operation must repeat for each iteration of an outer operation.