ASP Looping Structures

These examples include some simple representations of VBScript's looping structures. You can highlight, cut-and-paste any of code on the page and test it out on your web server. Be sure to save the file with the ".asp" suffix.

Below you can see some code for a VBScript Do/Loop Structure:


<%
'VBScript Example: Do/Loop Structure

Dim intLoopVar, intNumLoops

'Assign values to variables
intLoopVar = 1
intNumLoops = 5

'Perform function intNumLoops times
Do
	If intLoopVar = 1 Then 
		response.Write "How many times do I have to tell you?  " & intLoopVar & " time.
" Else response.Write "How many times do I have to tell you? " & intLoopVar & " times.
" End If intLoopVar = intLoopVar + 1 'You can use the Exit Do statement to prematurely exit a loop Loop Until intLoopVar > intNumLoops 'Until reverses logic (can also use While)
%>

Below is another looping structure, the For/Next Loop:


<%
'VBScript Example: For/Next Loops

Dim intStart, intStop, intCount

'Assign values to variables
intStart = 1
intStop = 10
intCount = 1

'Add a number while looping a selected number of times
For intCount = intStart To intStop Step 1 'Step not required
	Response.Write intCount & "
" Next 'intCount (varname not used in VBScript)
%>

Another looping structure is the While/Wend Loop, which isn't used as frequently as the above two. There are some limitation on the exiting of these loops, so use them with caution.


<%
'VBScript Example: While/Wend Structure

Dim intLoopVar, intNumLoops

'Assign values to variables
intLoopVar = 1
intNumLoops = 5

'Perform function intNumLoops times
While intLoopVar <= intNumLoops
	If intLoopVar = 1 Then 
		response.Write "How many times do I have to tell you?  " & intLoopVar & " time.
" Else response.Write "How many times do I have to tell you? " & intLoopVar & " times.
" End If intLoopVar = intLoopVar + 1 Wend 'Note: It's best to use the Do/Loop due to the exit ability
%>


Next