“Do While” and “For Next”
Statements
Manzione
“Do… Loop” Statements
• “Do… Loop” statements begin with a “Do”
keyword and end with a “Loop”
• 2 types of “Do” loops
– “While” and “Until”
• Primary use:
– To automate a program to read a block of statements
that are either ‘true until false’ or ‘false until true’
1
“Do While… Loop”
• A "Do While" loop statement runs while a
logical expression is true.
• This means that as long as your
expression stays true, your program will
keep on running.
• Once the expression is false, your
program stops running.
Example of “Do While… Loop”
Do While Expression
‘ Inserted code runs as long as the
expression is TRUE
Loop
Do While MsgBox (“Print the map?”, vbYesNo) = _
vbYes
‘ Code here that prints map
MsgBox “Printing Map”
Loop
2
“Do Until… Loop”
• A "Do Until" loop statement runs until a
logical statement is true.
• This means that as long as your
expression is false, the program will run
until it is true.
• Once the expression is true, the program
stops running.
Example of “Do Until… Loop”
Do Until Expression
‘ Inserted code runs as long as the
expression is FALSE
Loop
Do Until EOF (1)
‘ Read lines from the file
Loop
3
“For… Next” Statements
• “For… Next” statements begin with a “For”
keyword and end with a “Next”
• 2 types of “For” Statements
– “For… Next” and “For Each… Next”
• Primary use:
– To automate a program to read a block of statements
until the statement runs a given number of times as
determined by the start, end, and step values.
“For… Next” Statements
• You determine the range of values you
wish to loop ("StartValue" to "EndValue")
and allow the script to run until values go
from start to finish.
• Once the script runs its first variable, it is
looped by the "Next" statement.
• This statement tells the program to
procede to the next variable until it
reaches its EndValue.
4
Example of “For… Next”
For variable = StartValue To EndValue
‘ Block of code inserted here
Next
For x = 1 to 10
‘ Code to print file
MsgBox "Printing File " & x
Next
“For Each… Next” Statements
• “For Each… Next” Statements repeats a
group of statements for each element in
an array or collection
• With this command you tell the program to
repeat a function command for each given
element in a group listing.
5
Example of “For Each… Next”
For Each element In group
‘ Insert statement here
Next
‘ Display the list of field names in a message box
For Each fieldName In theList
MsgBox “The field name is “ & fieldName
Next fieldName
Text Pages
• Programming ArcObjects with VBA
– “Do… Loop” Statements: Pages 23-24
– “For… Next” Statements: Pages 24-25
• Getting to Know ArcObjects
– “Do… Loop” Statements: Pages 111-113
– “For… Next” Statements: Pages 104-105