Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 106 Computing Fundamentals II Chapter 73 “Ranges”

Similar presentations


Presentation on theme: "CS 106 Computing Fundamentals II Chapter 73 “Ranges”"— Presentation transcript:

1 CS 106 Computing Fundamentals II Chapter 73 “Ranges”
Herbert G. Mayer, PSU CS status 6/24/2013 Initial content copied verbatim from CS 106 material developed by CS professors: Cynthia Brown & Robert Martin

2 Syllabus Ranges Range is a Collection of Cells Use ForEach with Range
One-Dimensional Sample Two-Dimensional Sample

3 Ranges Unlike many of our programming concepts, Range is particular to Excel Look for more detail in demo ForEachForNext We show how to use a For Each loop with a Range, and contrast with a For variable nested loop that will help prepare us to deal with arrays

4 Range is a Collection of Cells
VBA in Excel has a data type Range A Range can be a single cell, a block of cells, or a group of blocks of cells (we’ll stick with the first two possibilities) You declare a Range variable in the usual way: Dim workArea As Range Dim aCell As Range

5 Use For Each with Range For Each loop is used when you want to do the same thing to every item in a collection A Range is a collection of cells This loop clears all cells in global range workArea: Sub ClearCells() Dim aCell As Range For Each aCell In workArea aCell.Value = Empty Next aCell End Sub

6 Put a 1 in Each Cell in a Range
Sub ForEachDemo() Dim aCell As Range For Each aCell In workArea aCell.Value = 1 Next aCell End Sub

7 Treat Cells Differently
If you don’t want to do the same thing with each cell, then use a different kind of loop For loops using variables work very well in this case For a range that is just a single row or column, one loop is fine For a two-dimensional range, you need nested loops

8 One-Dimensional Example (row)
To set elements 1 to size of the first row to two times their column index: For colNdx = 1 To size Cells(1, colNdx) = 2 * colNdx Next colNdx

9 Two-Dimensional Example
Sub ForVariableDemo() Dim rowNdx, colNdx As Long For rowNdx = 1 To size For colNdx = 1 To size Cells(rowNdx, colNdx).Value = rowNdx + colNdx Next colNdx Next rowNdx End Sub


Download ppt "CS 106 Computing Fundamentals II Chapter 73 “Ranges”"

Similar presentations


Ads by Google