Excel 2019 Power Programming with VBA. Michael Alexander

Читать онлайн книгу.

Excel 2019 Power Programming with VBA - Michael Alexander


Скачать книгу
For-Next loop. Its syntax is as follows:

      For counter = start To end [Step stepval] [instructions] [Exit For] [instructions] Next [counter]

      What is structured programming?

      Hang around with programmers, and sooner or later you'll hear the term structured programming. You'll also discover that structured programs are considered superior to unstructured programs.

      So, what is structured programming, and can you do it with VBA?

      The basic premise of structured programming is that a routine or code segment should have only one entry point and one exit point. In other words, a body of code should be a stand-alone unit, and program control should not jump into or exit from the middle of this unit. As a result, structured programming rules out the GoTo statement. When you write structured code, your program progresses in an orderly manner and is easy to follow—as opposed to spaghetti code, in which a program jumps around.

      A structured program is easier to read and understand than an unstructured one. More important, it's also easier to modify.

      VBA is a structured language. It offers standard structured constructs, such as If-Then-Else and Select Case and the For-Next, Do Until, and Do While loops. Furthermore, VBA fully supports modular code construction.

      If you're new to programming, form good structured programming habits early.

      Sub SumSquareRoots() Dim Sum As Double Dim Count As Integer Sum = 0 For Count = 1 To 100 Sum = Sum + Sqr(Count) Next Count MsgBox Sum End Sub

      In this example, Count (the loop counter variable) starts out as 1 and increases by 1 each time the loop repeats. The Sum variable simply accumulates the square roots of each value of Count.

      CAUTION

      When you use For-Next loops, it's important to understand that the loop counter is a normal variable—nothing special. As a result, it's possible to change the value of the loop counter in the block of code executed between the For and Next statements. Changing the loop counter inside a loop, however, is a bad practice and can cause unpredictable results. You should take precautions to ensure that your code doesn't change the loop counter.

      You can also use a Step value to skip some values in the loop. Here's the same procedure rewritten to sum the square roots of the odd numbers between 1 and 100:

      Sub SumOddSquareRoots() Dim Sum As Double Dim Count As Integer Sum = 0 For Count = 1 To 100 Step 2 Sum = Sum + Sqr(Count) Next Count MsgBox Sum End Sub

      In this procedure, Count starts out as 1 and then takes on values of 3, 5, 7, and so on. The final value of Count used in the loop is 99. When the loop ends, the value of Count is 101.

      A Step value in a For-Next loop can also be negative. The procedure that follows deletes rows 2, 4, 6, 8, and 10 of the active worksheet:

      Sub DeleteRows() Dim RowNum As Long For RowNum = 10 To 2 Step -2 Rows(RowNum).Delete Next RowNum End Sub

      Sub DeleteRows2() Dim RowNum As Long For RowNum = 2 To 10 Step 2 Rows(RowNum).Delete Next RowNum End Sub

      The following procedure performs the same task as the BadLoop example at the beginning of the “Looping blocks of instructions” section. We eliminate the GoTo statement, however, converting a bad loop into a good loop that uses the For-Next structure.

      Sub GoodLoop() Dim StartVal As Integer Dim NumToFill As Integer Dim iCount As Integer StartVal = 1 NumToFill = 100 For iCount = 0 To NumToFill - 1 ActiveCell.Offset(iCount, 0).Value = StartVal + iCount Next iCount End Sub

      For-Next loops can also include one or more Exit For statements in the loop. When this statement is encountered, the loop terminates immediately, and control passes to the statement following the Next statement of the current For-Next loop. The following example demonstrates the use of the Exit For statement. This procedure determines which cell has the largest value in Column A of the active worksheet:

      Sub ExitForDemo() Dim MaxVal As Double Dim Row As Long MaxVal = Application.WorksheetFunction.Max(Range("A:A")) For Row = 1 To 1048576 If Cells(Row, 1).Value = MaxVal Then Exit For End If Next Row MsgBox "Max value is in Row " & Row Cells(Row, 1).Activate End Sub

      NOTE

      The ExitForDemo procedure is presented to demonstrate how to exit from a For-Next loop. However, it's not the most efficient way to activate the largest value in a range. In fact, a single statement does the job.

      Range("A:A").Find(Application.WorksheetFunction.Max _ (Range("A:A"))).Activate

      The previous examples use relatively simple loops. But you can have any number of statements in the loop, and you can even nest For-Next loops inside other For-Next loops. Here's an example that uses nested For-Next loops to initialize a 10 × 10 × 10 array with the value –1. When the procedure is finished, each of the 1,000 elements in MyArray contains –1.

      Sub NestedLoops() Dim MyArray(1 to 10, 1 to 10, 1 to 10) Dim i As Integer, j As Integer, k As Integer For i = 1 To 10 For j = 1 To 10 For k = 1 To 10 MyArray(i, j, k) = -1 Next k Next j Next i ' [More code goes here] End Sub

      Do While loops

      This section describes another type of looping structure available in VBA. Unlike a For-Next loop, a Do While loop executes as long as a specified condition is met.

      A Do While loop can have either of two syntaxes. Here's the first:

      Do [While condition] [instructions] [Exit Do] [instructions] Loop

      Here's the second:

      Do [instructions] [Exit Do] [instructions] Loop [While condition]

      The following examples insert a series of dates


Скачать книгу