CS 106 Computing Fundamentals II Chapter 64 “For Loop Variations” Herbert G. Mayer, PSU CS Status 7/20/2013 Initial content copied verbatim from CS 106 material developed by CS professors: Cynthia Brown & Robert Martin
Syllabus Different For Loop Collections Changing the Increment Make Alternate Cells Blue
Different For Loop VBA has two kinds of For loops The first kind is controlled by a variable that is automatically incremented, and runs between a beginning and ending value The second kind is a For Each loop: it is executed for every member of a collection
Collections There are various types of collections in VBA. For example, open workbooks are a collection: Sub CloseInactive() Dim Book As Workbook For Each Book In Workbooks ‘ note “In” operator! If Book.Name <> ActiveWorkBook.Name Then Book.Close End If Next Book End Sub
Changing the Increment Our examples so far have used an increment of 1 for the control variable This is the default and no special code needs to be written for it You can also use other increments, using the Step keyword to control explicit step size different from 1
Make Alternate Cells Blue Const CHANGEROW As Long = 8 Const LASTCOL As Long = 10 Sub BlueSkip() Dim j As Long For j = 1 To LASTCOL Step 2 Cells( CHANGEROW, j ).Interior.Color = vbBlue Next j ‘ but its value is: j = j + 2 End Sub