Do While, Do Until and While...Wend Loops in Classic ASP

A Do...Loop repeats a block of VBScript statements while a condition is true, or until a condition becomes true. For a quick start, this Classic ASP example displays numbers from 1 to 10:

Dim my_num
my_num = 1
Do While my_num <= 10
    Response.Write my_num & "<br>"
    my_num = my_num + 1
Loop

The condition is checked before each iteration. Once my_num becomes 11, the loop stops. The following snippets belong inside an ASP <% ... %> script block; a complete page appears later.

VBScript Do...Loop syntax and types

VBScript supports four conditional forms of Do...Loop. The condition may appear at the start or at the end, and you can choose whether to repeat while the condition is true or until it becomes true.

Do While condition
    ' Run while condition is True
Loop

Do
    ' Run at least once, then test condition
Loop While condition

Do Until condition
    ' Run until condition becomes True
Loop

Do
    ' Run at least once, then test condition
Loop Until condition
StructureWhen to runCan run zero times?
Do While ... LoopKeep looping while the condition is TrueYes
Do ... Loop WhileRun first, then repeat while TrueNo
Do Until ... LoopKeep looping while the condition is FalseYes
Do ... Loop UntilRun first, then repeat until TrueNo

Unlike For...Next, which is useful when the number of iterations is known, a Do...Loop is useful for repeating an action until some changing condition is met.

Do While: check the condition before each iteration

In the original example, my_num starts at 1 and is increased by 1 on every pass. The loop stops after displaying 10 because the next test, 11 <= 10, is false.

Dim my_num
my_num = 1

Do While my_num <= 10
    Response.Write my_num & "<br>"
    my_num = my_num + 1
Loop

Output:

1
2
3
4
5
6
7
8
9
10

What happens if the first test is false?

Dim my_num
my_num = 11
Do While my_num <= 10
    Response.Write my_num & "<br>"
    my_num = my_num + 1
Loop

Nothing is displayed because the initial condition is already false. This is helpful when the code must not execute unless a requirement has been met.

Count backward with Do While

Dim my_num
my_num = 5
Do While my_num >= 1
    Response.Write my_num & " "
    my_num = my_num - 1
Loop

Output:

5 4 3 2 1

The update statement matters: when counting backward, decrease the counter. If you increase it instead, the condition might never become false.

Loop While: check the condition after execution

Moving While to the end changes the behavior. The statements execute at least once before the condition is checked. This preserves the original example where the starting number is 11.

Dim my_num
my_num = 11

Do
    Response.Write my_num & "<br>"
    my_num = my_num + 1
Loop While my_num <= 10

Output:

11

The result is 11, even though the condition is false at the first check. This is useful for an action that must happen once before deciding whether it needs to repeat, such as showing an initial prompt or reading an initial value.

Another post-test example

Dim tries
tries = 0
Do
    tries = tries + 1
    Response.Write "Attempt " & tries & "<br>"
Loop While tries < 3

Output:

Attempt 1
Attempt 2
Attempt 3

The condition is checked after printing each attempt. On the third pass, tries < 3 becomes false.

Do Until: repeat until the condition becomes true

The original tutorial also uses Do Until. Unlike Do While, it keeps running until the test becomes true. For example, start with 1 and stop when the counter becomes greater than 10:

Dim my_num
my_num = 1
Do Until my_num > 10
    Response.Write my_num & "<br>"
    my_num = my_num + 1
Loop

Output:

1
2
3
4
5
6
7
8
9
10

The loop runs while my_num > 10 is false. When my_num becomes 11, the condition becomes true and execution continues after Loop.

Do While and Do Until equivalents

Dim n
n = 1
Do While n <= 5
    Response.Write n & " "
    n = n + 1
Loop

Response.Write "<br>"
n = 1
Do Until n > 5
    Response.Write n & " "
    n = n + 1
Loop

Output:

1 2 3 4 5
1 2 3 4 5

Both examples produce the same sequence. Choose the condition that reads more naturally for your situation and make sure the counter changes toward that condition.

Loop Until: run once, then check the stopping condition

The condition can also appear at the end of an Until loop. This is useful when an action must occur before checking whether a stopping condition has been reached.

Dim my_num
my_num = 1
Do
    Response.Write my_num & " "
    my_num = my_num + 1
Loop Until my_num > 5

Output:

1 2 3 4 5

The loop still runs once if the condition begins as true

Dim my_num
my_num = 11
Do
    Response.Write my_num
    my_num = my_num + 1
Loop Until my_num > 10

Output:

11

The statements execute before the Until test, so the first pass is guaranteed. Use an opening test instead when a zero-iteration result is required.

While...Wend: the older VBScript loop

Classic ASP also supports While...Wend. This is a pre-test loop: it repeats while the condition is true. Unlike Do...Loop, it does not have an Exit Do equivalent. For new examples, Do While...Loop is usually easier to extend.

Dim counter
counter = 1
While counter <= 5
    Response.Write counter & " "
    counter = counter + 1
Wend

Output:

1 2 3 4 5
VBScript compatibility: Use While...Wend (not modern Visual Basic's While...End While). For an early exit, choose Do...Loop and Exit Do.

Exit Do: stop a loop before its condition changes

An Exit Do statement immediately stops the innermost active Do...Loop. This is useful when a match has been found or further processing is unnecessary. For decisions within loops, review If...Then...Else.

Dim my_num
my_num = 1
Do While my_num <= 10
    If my_num = 6 Then
        Exit Do
    End If
    Response.Write my_num & " "
    my_num = my_num + 1
Loop
Response.Write "<br>Stopped early"

Output:

1 2 3 4 5
Stopped early

Condition-free Do...Loop with Exit Do

A Do...Loop may omit the condition, but it must include a reliable exit path. Otherwise it can run indefinitely and consume server resources.

Dim counter
counter = 0
Do
    counter = counter + 1
    Response.Write counter & " "
    If counter >= 3 Then Exit Do
Loop

Output:

1 2 3

Classic VBScript does not support the newer Visual Basic Continue Do statement. To skip work for one pass, use an If block and let execution reach the next Loop test.

Skip an item without ending the loop

Dim counter
counter = 0
Do While counter < 5
    counter = counter + 1
    If counter <> 3 Then
        Response.Write counter & " "
    End If
Loop

Output:

1 2 4 5

Nested Do loops and arrays

Use an inner and outer loop

A Do...Loop can contain another loop. Each loop must update its own controlling variable to avoid getting stuck. This example prints a 3 by 3 multiplication pattern.

Dim rowNum, colNum
rowNum = 1
Do While rowNum <= 3
    colNum = 1
    Do While colNum <= 3
        Response.Write (rowNum * colNum) & " "
        colNum = colNum + 1
    Loop
    Response.Write "<br>"
    rowNum = rowNum + 1
Loop

Output:

1 2 3
2 4 6
3 6 9

The inner loop completes three passes for each outer pass. Exit Do exits only the innermost active loop; it does not automatically stop every enclosing loop.

Search a VBScript array until a match is found

A VBScript array can be searched with a Do While loop. The UBound() function supplies the highest array index. Stop early when the target value is found.

Dim countries, index, found
countries = Array("UK", "USA", "Canada", "UAE")
index = LBound(countries)
found = False

Do While index <= UBound(countries)
    If LCase(countries(index)) = "canada" Then
        found = True
        Exit Do
    End If
    index = index + 1
Loop

If found Then
    Response.Write "Found: " & Server.HTMLEncode(countries(index))
Else
    Response.Write "Not found"
End If

Output:

Found: Canada

This is a sequential search. For many array searches, built-in functions such as Filter() may be simpler, depending on the matching requirement.

Practical Classic ASP uses

Read lines from a text file until the end

Use Do While Not file.AtEndOfStream to process a text file until no lines remain. The following complete script assumes a test file named sample.txt exists in the same application folder; reading depends on IIS filesystem permissions. For more examples see FileSystemObject file handling.

<%
Const ForReading = 1
Dim fso, filePath, stream
filePath = Server.MapPath("sample.txt")
Set fso = Server.CreateObject("Scripting.FileSystemObject")

If fso.FileExists(filePath) Then
    Set stream = fso.OpenTextFile(filePath, ForReading)
    Do While Not stream.AtEndOfStream
        Response.Write Server.HTMLEncode(stream.ReadLine) & "<br>"
    Loop
    stream.Close
    Set stream = Nothing
Else
    Response.Write "Sample file not found"
End If
Set fso = Nothing
%>

Always close a file that was opened. Since each call to ReadLine moves the cursor forward, the loop can eventually reach AtEndOfStream. HTML-encoding prevents content from the text file from being interpreted as markup.

Process records returned from a database

A common use of Do Until is reading a database recordset until EOF (end of file/records). This excerpt assumes rs is an open ADODB.Recordset with a name field, created by connection code covered in ASP database records.

If Not rs.EOF Then
    Do Until rs.EOF
        If Not IsNull(rs("name").Value) Then
            Response.Write Server.HTMLEncode(CStr(rs("name").Value)) & "<br>"
        End If
        rs.MoveNext
    Loop
End If

The crucial line is rs.MoveNext; without advancing the recordset, EOF may never become true. Close the recordset and database connection in the surrounding database script when finished. The example is intentionally an excerpt rather than a standalone database application.

Use a safe iteration limit on a public website

When a loop handles unpredictable work, use a maximum iteration count as an additional safeguard. This does not replace correct stopping conditions or limits on external operations, but it prevents an unbounded counting loop.

Dim attempts, completed
attempts = 0
completed = False
Do While attempts < 5 And Not completed
    attempts = attempts + 1
    ' Do one attempt here
    If attempts = 3 Then completed = True
Loop
Response.Write "Attempts: " & attempts

Output:

Attempts: 3

Keep external work, such as database queries or network calls, subject to appropriate timeouts as well as iteration limits.

A complete standalone Classic ASP page

Place this example in a file such as loop-example.asp on a test IIS server with Classic ASP enabled. It includes the ASP delimiters and the surrounding HTML document.

<%@ Language="VBScript" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Do While example</title>
</head>
<body>
<h1>Counting with Do While</h1>
<%
Dim n
n = 1
Do While n <= 5
    Response.Write "<p>Number " & n & "</p>"
    n = n + 1
Loop
%>
</body>
</html>

The page renders five paragraphs, from Number 1 to Number 5. Each preceding small VBScript snippet is intended to run inside an existing ASP script block.

Troubleshooting and frequently asked questions

ProblemLikely cause and solution
Nothing is displayedA pre-test Do While or Do Until condition is already false/true. Check the initial value or use a post-test loop when one pass is required.
Page takes too long or does not finishThe condition never changes. Update the counter, advance a recordset with MoveNext, or introduce an appropriate stopping condition.
One extra value appearsCheck whether the condition is at the end (Loop While / Loop Until), where statements always run at least once.
Syntax error with a loop statementMatch every Do with Loop and every While with Wend. Do not mix the two forms.
Continue Do does not workThat is not a VBScript statement. Use an If...Then block to skip work on an iteration.
Unexpected or unsafe text outputUse Server.HTMLEncode() when displaying external or user-supplied text in HTML.

When should I use Do While instead of Do Until?

Do While emphasizes a condition that must remain true. Do Until emphasizes the condition that must eventually become true. You can often express the same control flow with either form by reversing the test.

What is the difference between Do While and Loop While?

With Do While, the condition is checked before the first pass and the loop may run zero times. With Loop While, the condition is checked after the code executes, so it runs at least once.

Can I use Exit Do inside a While...Wend loop?

No. Exit Do belongs to a Do...Loop. If early termination is required, use Do While...Loop or Do Until...Loop.

Can a Do...Loop run forever?

Yes. A missing or ineffective update, or a condition that never changes, can create an endless loop. On a web server, use an explicit stopping condition and appropriate resource limits.

Does Classic ASP support Continue Do?

No. Do not copy the Continue Do examples from modern Visual Basic into Classic ASP. Use If...Then to guard the work instead.

Which loop should I use to display array items?

Do While works when you need an index and want to stop under a condition. For simply visiting every item, For...Next or a For Each loop may be clearer.

For language-level reference, consult the VBScript Do...Loop statement documentation.

Back to top ↑


ASP Home






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer