Академический Документы
Профессиональный Документы
Культура Документы
Introduction to Looping
David Rossiter, Gibson Lam and Eddie Chan
What is Looping?
A loop is a set of code which repeats many times
Looping is a very useful feature in programming
languages such as VBA because it makes repetitive
work easier
For example, you can use a nested
loop to generate a chess board
In this presentation we will look
at two types of loops:
While Loops
Do Loops
WhileWend
While . . .condition. . .
. . .statement(s). . .
Wend
While condition is true, repeatedly execute
statement(s)
When condition is false, WhileWend finishes
COMP1022Q
Introduction to Looping
Page 3
Is condition true?
yes
Execute
statement(s)
no
COMP1022Q
Introduction to Looping
Page 6
Next
iteration
Next
iteration
Next
iteration
Next
iteration
Do WhileLoop
Do While . . .condition. . .
. . .statement(s). . .
Loop
The usage of Do WhileLoop is exactly the same as
WhileWend
The difference is that the keywords of Do
WhileLoop are more English than WhileWend
COMP1022Q
Introduction to Looping
Page 17
Is condition true?
yes
Execute
statement(s)
no
Example of Do WhileLoop
For example, we can create a program which does the same
thing as the WhileWend example using Do WhileLoop:
' Select the first cell in the 4th row
Cells(4, 1).Select
Loop condition
Do While ActiveCell.Row <= 10
' Put the row number into the first cell
ActiveCell.Value = "I am row " & _
ActiveCell.Row
Loop
body
' Move the selection down one cell
ActiveCell.Offset(1, 0).Select
Loop
DoLoop While
Do
. . .statement(s). . .
Loop While . . .condition. . .
This is similar to the previous two loops we looked at
but condition is evaluated after statement(s) is
executed
This means that statement(s) will be executed at least
once before condition is evaluated
COMP1022Q
Introduction to Looping
Page 20
Execute
statement(s)
yes
Is condition true?
no