Using Loops
Loops are used to execute a block of program
statement a number of times, or until a
condition occurs. The For…Next Loop
is used to execute a number of times; the Do Loop and Do While Loop is used to loop
until a condition occurs. The Do Loop tests for the condition after
completing the loop statements once, the Do While loop tests for the
condition before doing the loop, even on the first pass.
What is the drawback of loops? You can
accidentally create program code that cannot release itself from the
loop! You must consider how the loop will end, and make sure
that condition will occur!
For…Next Loops
Syntax:
For variable = start to end
Program Statements
Next
The variable must be an integer. The any
program statements can be used between the For
and the Next lines; do indent them though. VB will take care of
incrementing the variable for you automatically.
Counter
In the top section, declare the counter
variable, so that it will carry a value independent of any
subroutine.
Dim X as integer = 1
Program Code for button 1 click
Picturebox1.image =
system.drawing.image.fromfile _
(“c:\picture\face” & X & “.gif”)
X += 1
If X = 5 then X = 1
What it does:
When the user clicks button 1, face1.gif will
appear. X will become 2. The value of X will be inspected to
see if it is 5. If it is 5, then it will be reset to 1.
When the user clicks button 1 again, face2.gif will appear. X will become 3. The value of X will
be inspected to see if it is 5. If it is 5, then it will be
reset to 1.
The 4 pictures will be shown, with the user
setting the pace by clicking button 1.
Note:
-
X += 1 This is the new way to increment X
in Visual Basic 2005.
-
It is the same as X = X + 1
-
Do While Loop
The Do While loop tests a condition then
proceeds through through the loop if the
condition is true.
Syntax:
Do
While condition
Block of program statements go here
Loop
Example:
This does the same thing as the Counter
example. It opens four image files. I added the
msgBox so that you can see each picture.
Otherwise it would do them all very fast, and you might not even see
it.
Do Loop
The Do loop tests for the condition after
completing the loop once. The condition will not be evaluated
until the loop is completed.
Syntax:
Do
Block of program
statements go here
Loop
While condition
Example: