Presentation is loading. Please wait.

Presentation is loading. Please wait.

CE En 270 Brigham Young University Norm Jones

Similar presentations


Presentation on theme: "CE En 270 Brigham Young University Norm Jones"— Presentation transcript:

1 CE En 270 Brigham Young University Norm Jones
Loops – Lecture #1

2 Applications Traversing through a range of cells or a collection of objects in a systematic fashion Doing calculations that require iterations Repeating actions until some condition is met

3 Types of Loops in VB For Each… For i=1 To … Do While… Do Until…

4 For Each … Loops For Each… loops are used to loop through a set of items. For example Cells in a range Objects in a collection We have already used For Each… loops, but let’s review them

5 For Each… Syntax Dim myitem As Variant For Each myitem In mycollection
statement(s) Next myitem

6 Example 1: For Each… Dim mycell As Range
For Each mycell In Range(“B4:D20”) If mycell.Value < 0 Then numneg = numneg + 1 End If Next mycell

7 Example 2: For Each… Dim sh As Shape For Each sh In Shapes
sh.Fill.ForeColor.RGB = vbRed Next sh

8 For i= … Loops For i=… loops are used in situations when you know exactly how many times you need to go through the loop They are useful for traversing through cells or for making computations

9 For i=… Syntax Dim i As Integer For i = Start To End Step inc
statement(s) Next i Optional

10 Example 1: For i=… Dim myrow As Integer For myrow = 3 To 17
Cells(myrow, 2) = "Hello" Next myrow

11 Example 2: For i=… Dim myrow As Integer For myrow = 17 To 3 Step -1
Cells(myrow, 2) = "Hello" Next myrow

12 Example 3: For i=… Dim i As Integer Dim sum As Integer
For i = 1 To 100 sum = sum + i Next i

13 Exit For Statement You can exit any “For" loop at any time using the Exit For statement This kicks you out of the loop and it moves the execution to the next statement just outside the loop


Download ppt "CE En 270 Brigham Young University Norm Jones"

Similar presentations


Ads by Google