Download presentation
Presentation is loading. Please wait.
1
CE En 270 Brigham Young University Norm Jones
Loops – Lecture #2
2
Do Loops Do loops are a simple and versatile method to do looping
Generally used when you don’t know beforehand how many times you will be going through the loop
3
Do Loop Syntax OR Do While|Until condition statement(s) Loop Do
Loop While|Until condition
4
Do Loop Examples The following VB snippets are used to start at row 4 and loop through the cells in column A until a blank (empty) cell is found Each of the following examples achieves the same result Start here Stop here
5
Method 1: Do While… Dim myrow As Integer myrow = 4
Do While Cells(myrow, 1) <> "" myrow = myrow + 1 Loop
6
Method 2: Do Until… Dim myrow As Integer myrow = 4
Do Until Cells(myrow, 1) = "" myrow = myrow + 1 Loop
7
Method 3: Do … Loop While Dim myrow As Integer myrow = 3 Do
myrow = myrow + 1 Loop While Cells(myrow, 1) <> ""
8
Method 4: Do … Loop Until Dim myrow As Integer myrow = 3 Do
myrow = myrow + 1 Loop Until Cells(myrow, 1) = ""
9
Differences If you put the condition at the end (Do … Loop While|Until condition) then the loop will always be executed at least once If you put the condition at the beginning (Do While|Until condition … Loop), then the loop may be executed zero times depending on the situation
10
Infinite Loops When writing your loops, make sure you are doing something in the code (incrementing a counter for example) that ensures that the exit condition will eventually be met Otherwise, you will have an “infinite loop” and it will loop forever or until you kill or interrupt Excel (use Esc key)
11
Boolean Variables Recall that a Boolean variable is a variable that has a value of either True or False Boolean variables can be useful when writing loops
12
Example Dim myrow As Integer Dim found As Boolean myrow = 4
found = False Do Until found If Cells(myrow, 4) = "" Then found = True Else myrow = myrow + 1 End If Loop
13
Exit Do Statement You can exit any "Do" loop at any time using the Exit Do statement This kicks you out of the loop and it moves the execution to the next statement just outside the loop
14
Example Dim myrow As Integer myrow = 4 Do Until myrow = 32768
If Cells(myrow, 1) = "" Then Exit Do Else myrow = myrow + 1 End If Loop
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.