Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA While Loop: How to Use It

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

A VBA While loop repeats a block of code as long as a condition is true. You write While condition, put the statements you want to repeat underneath, and finish with Wend. The loop checks the condition before the first pass, so if the condition is false at the start, the code inside never runs. That is the whole idea: keep doing something until the test says stop.

This guide covers the two forms of the loop (While...Wend and Do While...Loop), how to avoid the classic infinite loop, and the mistakes that make Excel freeze or produce wrong totals. Everything here works in the Visual Basic Editor that ships with Excel on Windows and Mac; the editor window looks slightly different between versions, but the code is the same.

What You'll Need

  • Excel with macros enabled (the desktop app, not Excel for the web, which cannot run VBA).
  • The Developer tab visible, or another way to open the Visual Basic Editor (Alt+F11 on Windows, Option+F11 on Mac).
  • A workbook saved as .xlsm if you want to keep the macro.
  • A basic idea of variables and cell references, such as Range("A1").Value.

Step-by-Step

  1. Open the editor. Press Alt+F11 (Windows) or Option+F11 (Mac) to open the Visual Basic Editor. In the Project Explorer, right-click your workbook and choose Insert > Module. A blank code window appears.
  2. Start a Sub procedure. Type Sub LoopExample() and press Enter. The editor adds End Sub automatically. All your code goes between these two lines.
  3. Declare a counter variable. Add Dim i As Long on the first line inside the Sub. Use Long rather than Integer; it avoids overflow errors on large loops.
  4. Set the starting value. Add i = 1. The loop needs a known starting point, otherwise the condition is tested against an empty variable (which VBA treats as zero, but relying on that is poor practice).
  5. Write the While line. Add While i <= 10. This is the condition. The loop runs while it is true. You can test any expression that returns True or False, such as While Range("A" & i).Value <> "" to walk down a column until a blank cell.
  6. Add the body. Indent and add the statements you want repeated. For example, Cells(i, 2).Value = i * 2 writes the doubles into column B. You can have as many lines as you need.
  7. Change something the condition depends on. Add i = i + 1 as the last line inside the loop. This is the step that eventually makes the condition false. Without it the loop never ends and Excel stops responding.
  8. Close the loop. Type Wend on its own line. The structure is now While ... Wend with the body in between.
  9. Run it. Press F5. The macro fills B1 to B10 with 2, 4, 6 and so on up to 20, then stops because i becomes 11 and the condition fails.
  10. Try the Do form. The modern alternative is Do While i <= 10 ... Loop. It does the same thing but is easier to read and supports Exit Do to break out early. Do Until i > 10 ... Loop runs until the condition becomes true, which is the mirror image.
  11. Test the false-at-start case. Change the starting value to 11 and run again. Nothing is written, because the condition is checked before the first pass. If you need the body to run at least once, use Do ... Loop While i <= 10, which tests at the bottom.
  12. Save the workbook as .xlsm. Use File > Save As and choose Excel Macro-Enabled Workbook. A plain .xlsx save discards the module.

Common Mistakes

  • Forgetting to increment the counter. The single most common cause of a frozen Excel window. Every While loop needs something inside it that moves the condition toward False.
  • Incrementing in the wrong place. If i = i + 1 sits before the body, the first row is skipped. Put it after the statements that use i.
  • Testing a value that never changes. While Range("A1").Value <> "" loops forever if A1 is never cleared, because the cell is read fresh each pass but nothing writes to it.
  • Using Wend with Do syntax. Do While ... Wend is a syntax error. Match the opener to the closer: While with Wend, Do with Loop.
  • Off-by-one errors. While i < 10 stops at 9, not 10. Decide whether you want < or <= before you write the body.
  • No escape route. Long loops with no Exit Do or Exit Sub can hang for minutes on large ranges. Add a safety counter, for example stop after 10,000 passes.

Tips

  • Prefer Do While ... Loop over While ... Wend. It is the form Microsoft's own documentation recommends, it supports Exit Do, and it reads more clearly.
  • Turn off screen updating while the loop runs: Application.ScreenUpdating = False at the start and True at the end. It makes loops over hundreds of rows noticeably faster.
  • For looping over a fixed collection of cells, a For Each loop is usually simpler and safer than a While loop, because it cannot run forever.
  • Use Debug.Print i to watch the counter in the Immediate window (Ctrl+G) when a loop behaves unexpectedly.
  • Press Ctrl+Break to interrupt a runaway loop. If Excel is completely frozen, close it from Task Manager; unsaved work is lost, so save before running new code.

Troubleshooting

Excel freezes when you run the macro. Press Ctrl+Break. If that does nothing, the loop has no exit condition; close Excel and add an increment or a safety counter before running again.

"Compile error: Expected: Wend" or "Expected: Loop". The opener and closer do not match. Check whether you started with While or Do and close with the matching keyword.

The loop runs but writes nothing. The condition is false on entry. Check the starting value and the comparison operator.

Wrong number of rows filled. Look at < versus <= and at where the increment sits relative to the body.

"Overflow" error. The counter exceeded the range of its type. Declare it as Long, not Integer.

Macro missing after reopening. The file was saved as .xlsx. Save as .xlsm and enable macros when prompted.

Frequently Asked Questions

What is the difference between While...Wend and Do While...Loop?

They behave the same for simple cases. Do While...Loop is the newer, preferred form because it supports Exit Do and is easier to combine with other loop types. While...Wend is kept for backward compatibility.

How do I stop a While loop early?

Use Exit Do inside a Do While loop. The While...Wend form has no equivalent, which is one reason to prefer Do.

Can a While loop run zero times?

Yes. The condition is tested before the first pass, so a false condition skips the body entirely. Use Do ... Loop While if the body must run at least once.

How do I loop until a cell is empty?

Test the cell in the condition, for example Do While Cells(i, 1).Value <> "", and increment i inside the loop. Make sure nothing in the body fills that cell, or the loop will never end.

Why does my macro hang after a few seconds?

Almost always an infinite loop. The condition never becomes false because the variable it tests is not updated. Add the increment and test again.

Does VBA While work in Excel for the web?

No. Excel for the web cannot run VBA macros. Open the workbook in the desktop app to run or edit the code.