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 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
| Structure | When to run | Can run zero times? |
|---|---|---|
Do While ... Loop | Keep looping while the condition is True | Yes |
Do ... Loop While | Run first, then repeat while True | No |
Do Until ... Loop | Keep looping while the condition is False | Yes |
Do ... Loop Until | Run first, then repeat until True | No |
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.
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
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.
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.
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.
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.
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.
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.
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
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.
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
While...Wend (not modern Visual Basic's While...End While). For an early exit, choose Do...Loop and Exit Do.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
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.
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
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.
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.
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.
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.
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.
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.
| Problem | Likely cause and solution |
|---|---|
| Nothing is displayed | A 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 finish | The condition never changes. Update the counter, advance a recordset with MoveNext, or introduce an appropriate stopping condition. |
| One extra value appears | Check whether the condition is at the end (Loop While / Loop Until), where statements always run at least once. |
| Syntax error with a loop statement | Match every Do with Loop and every While with Wend. Do not mix the two forms. |
Continue Do does not work | That is not a VBScript statement. Use an If...Then block to skip work on an iteration. |
| Unexpected or unsafe text output | Use Server.HTMLEncode() when displaying external or user-supplied text in HTML. |
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.
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.
No. Exit Do belongs to a Do...Loop. If early termination is required, use Do While...Loop or Do Until...Loop.
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.
No. Do not copy the Continue Do examples from modern Visual Basic into Classic ASP. Use If...Then to guard the work instead.
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.