Curious Minds

Clear answers to science and history questions

Do While Statement in VBA: Syntax and Examples

· 6 min read · Science

Yes. VBA has a Do While loop, which repeats a block of code as long as a specified condition is True. Use it when the number of repetitions is not known in advance, such as processing rows until a blank cell is reached. VBA also supports Do Until, which repeats while a condition is False.

What a Do While loop does

A Do While loop checks a condition and runs its body while that condition remains True. The condition can compare values, test a variable, or evaluate a Boolean expression. When the condition becomes False, execution continues with the statement after Loop.

For example, a loop can increase a counter until it reaches a limit. It can also examine a worksheet one row at a time until it finds an empty cell. Because the condition controls whether the loop continues, its logic and the code that changes the condition are both important.

Basic syntax and a counter example

The condition can appear immediately after Do or after Loop. In the first form, VBA checks before running the body; in the second, it checks after running the body.

Sub CountToFive()
    Dim number As Long

    number = 1
    Do While number <= 5
        Debug.Print number
        number = number + 1
    Loop
End Sub

This example prints 1 through 5 in the Immediate window. The test is true when number is 1, 2, 3, 4, or 5. After the value increases to 6, the condition is False and the loop ends. To view output in the Visual Basic Editor, open the Immediate window with Ctrl+G on Windows.

The counter is initialized before the loop and changed inside it. Without the increment, the condition would stay True and the procedure would not finish normally.

Pre-test and post-test loops

These are the two main forms of a Do While loop:

  • Do While condition ... Loop checks before the first pass. If the condition starts False, the body runs zero times.
  • Do ... Loop While condition checks at the end. The body runs at least once, even if the condition is False by the time VBA checks it.

Choose a pre-test loop when the body should run only if the condition is initially satisfied. Choose a post-test loop when one pass is required before deciding whether to repeat—for example, when a user must be prompted once before their response can be checked.

Sub ShowAtLeastOnce()
    Dim answer As String

    Do
        answer = InputBox("Type yes to continue")
    Loop While LCase$(answer) = "yes"
End Sub

This prompt appears at least once. If the response is “yes,” ignoring letter case, it appears again. If the user cancels, InputBox returns an empty string, so the condition is False and the loop ends.

Example: process worksheet rows

A practical Excel use is to continue down a column until the first blank cell. This example checks column A starting at row 2 and writes a status in column B. It stops at the first blank in column A, so a blank within the data also ends processing.

Sub MarkRowsUntilBlank()
    Dim ws As Worksheet
    Dim rowNumber As Long

    Set ws = ThisWorkbook.Worksheets("Sheet1")
    rowNumber = 2

    Do While Len(ws.Cells(rowNumber, "A").Value) > 0
        ws.Cells(rowNumber, "B").Value = "Checked"
        rowNumber = rowNumber + 1
    Loop
End Sub

Change Sheet1 to the actual worksheet name. The Len test treats a cell containing a formula that returns an empty string as blank. If the data may contain gaps, a loop that stops at the first blank is not suitable; instead, determine the last used row and loop to that row, or define another stopping rule. Also consider whether spaces should count as content: a cell containing spaces has a nonzero length.

Do While compared with Do Until and For

Do Until condition repeats until the condition becomes True. It is the logical counterpart of Do While: use the version that makes the continuation rule clearest. For example, “keep going while the cell is not blank” may be easier to read as Do While; “keep going until the cell is blank” may be clearer as Do Until.

A For...Next loop is usually clearer when the number of passes is known or can be expressed as a range, such as rows 2 through 100. A Do While loop is useful when a condition determines when to stop and that endpoint is not known beforehand. VBA also offers For Each...Next for visiting each object in a collection, such as every worksheet in a workbook.

Common mistakes and safe use

  • Condition never changes: Make sure the loop body updates a variable or value that can eventually make the condition False.
  • Wrong comparison: Check boundary operators such as < versus <=. A small difference can add or omit a pass.
  • Wrong loop form: A condition after Loop always allows one pass; a condition after Do may allow none.
  • Unexpected cell values: Empty strings, errors, spaces, and numbers may require different tests. Validate the kind of data the loop will encounter.
  • Unbounded processing: If a loop should have a maximum number of passes, add a separate limit or other exit condition so unexpected input cannot keep it running indefinitely.

To stop a running macro in the VBA editor, use Ctrl+Break on Windows where available. On Mac, the interruption shortcut can vary by keyboard and Excel setup; the Visual Basic Editor’s Run menu provides a Reset command. Resetting interrupts execution, but it does not reverse changes already made to cells.

Before running a macro, save a copy of the workbook. VBA actions generally cannot be undone with Ctrl+Z, and a loop that writes to many cells can make extensive changes before it stops. Macros must be run in desktop Excel; Excel for the web cannot create, edit, or run VBA macros. On Mac desktop Excel, VBA is available, though editor shortcuts and some platform-specific automation features can differ from Windows.

Frequently Asked Questions

Does VBA have a Do While loop?
Yes. VBA supports both Do While condition ... Loop and Do ... Loop While condition. The first checks before each pass; the second checks after each pass.

What is the difference between Do While and Do Until?
Do While repeats while its condition is True. Do Until repeats while its condition is False and stops when it becomes True. Either can express many of the same stopping rules.

Can a Do While loop run zero times?
Yes, if the condition is placed after Do and is False at the initial check. A condition placed after Loop is tested only after the body, so that form runs at least once.

Why does my Do While loop never stop?
Usually, the condition remains True because the code does not update the value being tested, or because the update moves it in the wrong direction. Check the starting value, comparison operator, and each statement that changes the condition.

Should I use Do While or For Next in Excel VBA?
Use For...Next when you know the number or range of iterations. Use Do While when repetition should continue until a changing condition is met, such as reaching a blank cell or a user-selected stopping point.

In this article
  1. What a Do While loop does
  2. Basic syntax and a counter example
  3. Pre-test and post-test loops
  4. Example: process worksheet rows
  5. Do While compared with Do Until and For
  6. Common mistakes and safe use
  7. Frequently Asked Questions