Execute commands multiple times
In many cases it can be handy to execute a piece of code multiple times. For example when you want
to show the values from an array. You can use the same code everytime, as long as you change the index.
This is especially handy when you don't know in advance how many values an array contains.
You can execute commands multiple time with loops. There are two kinds of loops, one that executes
a certain amount of times and one that executes until a certain condition
is met (or as long as a certain condition hasn't been met). The first one is called a
For ... Next loop, the other one a Do ... Loop loop. Below we
'll discuss them both.
For ... Next
A For ... Next loop works on the basis of a counter that we declare first. The next step
is to indicate where the counter has to start and where it has to end. This counter will be raised with
one everytime the commands are executed, until the highest value has been reached. The
counter can also be raised by more than one for each iteration. The example below is very easy.
The index will be written to the browser with each step (with a an HTML break or line feed).
fornext1.asp
<%
Option Explicit
Dim i
%>
<HTML>
<BODY>
<%
For i = 1 To 20
Response.Write i & "<br>"
Next
%>
</BODY>
</HTML>
As said arrays and loops go well together. You can see this in the sample below.
In the sample we use the Split function to transform a string with
values separated by commas to an array. Then we use the UBound function
to get the highest index in the array.
fornext2.asp
<%
Option Explicit
Dim i
Dim strValues
Dim aValues
Dim lngNumber
strWaarden = "John,Pete,Mark,Pat"
aWaarden = Split(strValues, ",")
lngAantal = UBound(aValues)
%>
<HTML>
<BODY>
<%
For i = 0 To lngAantal
Response.Write aValues(i) & "<br>"
Next
%>
</BODY>
</HTML>
Do ... Loop
Do ... Loop has more possibilities than
For ... Next, but you also have to do more yourself. You have to decide
on the conditions yourself to execute the code (again). If you're using a counter you also have
to raise it yourself. If you forget this, the loop will go on endlessly. We give you two samples:
doloop1.asp
<%
Option Explicit
Dim i
%>
<HTML>
<BODY>
<%
i = 1
Do While i < 21
Response.Write i & "<br>"
i = i + 1
Loop
%>
</BODY>
</HTML>
doloop2.asp
<%
Option Explicit
Dim i
%>
<HTML>
<BODY>
<%
i = 1
Do
Response.Write i & "<br>"
i = i + 1
Loop Until i = 21
%>
</BODY>
</HTML>
In the second example you know that the commands will be executed at least once. In the
first example that's not the case. Furthermore While and
Until are exchangeable. It depends on the situation which one is
handier to use.
|