5. Looping and Flow Control

Loops are a fundamental component of any programming language. If you’ve taken any programming classes, even BASIC, you’ve likely encountered a For...Next loop. Fortunately, VBA supports all the usual loops, plus a special loop that is excellent to use with VBA.

This chapter covers the basic loop constructs:

For...Next

Do...While

Do...Until

While...Loop

Until...Loop

This chapter also discusses the useful loop construct that is unique to object-oriented languages:

For Each...Next

For...Next Loops

For and Next are common loop constructs. Everything between For and Next is run multiple times. Each time the code runs, a certain counter variable, specified in the For statement, has a different value.

Consider this code:

For I = 1 to 10
    Cells(I, I).Value = I
Next I

As this program starts to run, you need to give the counter variable a name of I. The first time through the code, the variable I is set to 1. The first time that the loop is executed, I is equal to 1, so the cell in Row 1, Column 1 will be set to 1 (see Figure 5.1).

image

Figure 5.1. After the first iteration through the loop, the cell in Row 1, Column 1 has the value of 1.

Let’s take a close look at what happens as VBA gets to the line that says Next I. Before running this line, the variable I is equal to 1. During the execution of Next I, VBA must make a decision. VBA adds 1 to the variable I and compares it to the maximum value in the To clause of the For statement. If it is within the limits specified in the To clause, the loop is not finished. In this case, the value of I will be incremented to 2. Code execution then moves back to the first line of code after the For statement. Figure 5.2 shows the state of the program before running the Next line. Figure 5.3 shows what happens after executing the Next line.

image

Figure 5.2. Before running the Next I statement, I is equal to 1. VBA can safely add 1 to I, and it will be less than the 10 specified in the To clause of the For statement.

image

Figure 5.3. After running the Next I statement, I is incremented to 2. Code execution continues with the line of code immediately following the For statement, which writes a 2 to cell B2.

The second time through the loop, the value of I is 2. The cell in Row 2, Column 2 (that is, cell B2) gets a value of 2.

As the process continues, the Next I statement advances I up to 3, 4, and so on. On the tenth pass through the loop, the cell in Row 10, Column 10 is assigned a value of 10.

It is interesting to watch what happens to the variable I on the last pass through Next I. In Figure 5.4, you can see that before executing Next I the tenth time, the variable I is equal to 10.

image

Figure 5.4. Before running Next I for the tenth time, the variable I is equal to 10.

VBA is now at a decision point. It adds 1 to the variable I. I is now equal to 11, which is greater than the limit in the For...Next loop. VBA then moves execution to the next line in the macro after the Next statement (see Figure 5.5). In case you are tempted to use the variable I later in the macro, it is important to realize that it might be incremented beyond the limit specified in the To clause of the For statement.

image

Figure 5.5. After incrementing I to 11, code execution moves to the line after the Next statement.

The common use for such a loop is to walk through all the rows in a dataset and decide to perform some action based on some criteria. For example, if you want to mark all the rows with positive service revenue in Column F, you could use this loop:

image

This loop checks each item of data from Row 2 through Row 10. If there is a positive number in Column F, Column H of that row will have a new label, and the cells in Columns A:H of the row will be colored green. After running this macro, the results look like Figure 5.6.

image

Figure 5.6. After the loop completes all nine iterations, any rows with positive values in Column F are colored green and have the label “Service Revenue” added to Column H.

Using Variables in the For Statement

The previous example is not very useful in that it works only when there are exactly 10 rows of data. It is possible to use a variable to specify the upper/lower limit of the For statement. This code sample identifies FinalRow with data and then loops from Row 2 to that row:

image


Caution

Exercise caution when using variables. What if the imported file today is empty and has only a heading row? In this case, the FinalRow variable is equal to 1. This makes the first statement of the loop essentially say For I = 2 to 1. Because the start number is higher than the end number, the loop does not execute at all. The variable I is equal to 2, and code execution jumps to the line after Next.


Variations on the For...Next Loop

In a For...Next loop, it is possible to have the loop variable jump up by something other than 1. For example, you might use it to apply green-bar formatting to every other row in a dataset. In this case, you want to have the counter variable I examine every other row in the dataset. Indicate this by adding the Step clause to the end of the For statement:

image

While running this code, VBA adds a light green shading to Rows 2, 4, 6, and so on (see Figure 5.7).

image

Figure 5.7. The Step clause in the For statement of the loop causes the action to occur on every other row.

image To see a demo of this macro, search for Excel VBA 5 at YouTube.

The Step clause can be any number. You might want to check every tenth row of a dataset to extract a random sample. In this case, you would use Step 10:

image

You can also have a For...Next loop run backward from high to low. This is particularly useful if you are selectively deleting rows. To do this, reverse the order of the For statement and have the Step clause specify a negative number:

image


Note

There is a faster way to delete the records, which is discussed in Chapter 12, “Deleting Records Using a Filter.”


Exiting a Loop Early After a Condition Is Met

Sometimes you don’t need to execute the whole loop. Perhaps you just need to read through the dataset until you find one record that meets a certain criteria. In this case, you want to find the first record and then stop the loop. A statement called Exit For does this.

The following sample macro looks for a row in the dataset where service revenue in Column F is positive and product revenue in Column E is 0. If such a row is found, you might indicate a message that the file needs manual processing today and move the cell pointer to that row:

image

Nesting One Loop Inside Another Loop

It is okay to run a loop inside another loop. The following code has the first loop run through all the rows in a recordset, while the second loop runs through all the columns:

image

In this code, the outer loop is using the I counter variable to loop through all the rows in the dataset. The inner loop is using the J counter variable to loop through all the columns in that row. Because Figure 5.8 has seven data rows, the code runs through the I loop seven times. Each time through the I loop, the code runs through the J loop six or seven times. This means that the line of code that is inside the J loop ends up being executed several times for each pass through the I loop. Figure 5.8 shows the result.

image

Figure 5.8. The result of nesting one loop inside the other; VBA can loop through each row and then each column.

Do Loops

There are several variations of the Do loop. The most basic Do loop is useful for doing a bunch of mundane tasks. For example, suppose someone sends you a list of addresses going down a column, as shown in Figure 5.9.

image

Figure 5.9. It would be more useful to have these addresses in a database format to use in a mail merge.

In this case, you might need to rearrange these addresses into a database with name in Column B, street in Column C, city and state in Column D. By setting Relative Recording (see Chapter 1, “Unleash the Power of Excel with VBA”) and using a hot key of Ctrl+A, you can record this bit of useful code. The code is designed to copy one single address into database format. The code also navigates the cell pointer to the name of the next address in the list. Each time you press Ctrl+A, one address will be reformatted.

image


Note

Do not assume that the preceding code is suitable for a professional application. However, sometimes macros are written just to automate a one-time mundane task.


Without a macro, a lot of manual copying and pasting would be required. However, with the preceding recorded macro, you can simply place the cell pointer on a name in Column A and press Ctrl+Shift+A. That one address will be copied into three columns, and the cell pointer will move to the start of the next address (see Figure 5.10).

image

Figure 5.10. After running the macro once, one address is moved into the proper format, and the cell pointer is positioned to run the macro again.

When you use this macro, you will be able to process an address every second using the hot key. However, when you need to process 5,000 addresses, you will not want to keep running the same macro over and over.

In this case, a Do...Loop can be used to set up the macro to run continuously. You can have VBA run this code continuously by enclosing the recorded code with Do at the top and Loop at the end. Now you can sit back and watch the code perform this insanely boring task in minutes rather than hours.

Note that this particular Do...Loop will run forever because there is no mechanism to stop it. This will work for the task at hand because you can watch the progress on the screen and press Ctrl+Break to stop execution when the program advances past the end of this database.

This code uses a Do loop to fix the addresses.

image

These examples are “quick and dirty” loops that are great for when you need to accomplish a task quickly. The Do...Loop provides a number of options to allow you to have the program stop automatically when it accomplishes the end of the task.

The first option is to have a line in the Do...Loop that detects the end of the dataset and exits the loop. In the current example, this could be accomplished by using the Exit Do command in an If statement. If the current cell is on a cell that is empty, you can assume that you have reached the end of the data and stopped processing the loop:

image

Using the While or Until Clause in Do Loops

There are four variations of using While or Until. These clauses can be added to either the Do statement or the Loop statement. In each case, the While or Until clause includes some test that evaluates to True or False.

With a Do While <test expression>...Loop construct, the loop is never executed if <test expression> is false. If you are reading records from a text file, you cannot assume that the file has one or more records. Instead, you need to test to see whether you are already at the end of file with the EOF function before you enter the loop:

image

In this example, the Not keyword EOF(1) evaluates to True after there are no more records to be read from Invoice.txt. Some programmers believe it is hard to read a program that contains a lot of Nots. To avoid the use of Not, use the Do Until <test expression> ...Loop construct:

image

In other examples, you might always want the loop to be executed the first time. In these cases, move the While or Until instruction to the end of the loop. This code sample asks the user to enter sales amounts made that day. It continually asks them for sales amounts until they enter a zero:

image

In the following loop, a check amount is entered, and then it looks for open invoices to which the check can be applied. However, it is often the case that a single check is received that covers several invoices. The following program sequentially applies the check to the oldest invoices until 100 percent of the check has been applied:

image

Because you can construct the Do...Loop with the While or Until qualifiers at the beginning or end, you have a great deal of subtle control over whether the loop is always executed once, even when the condition is true at the beginning.

While...Wend Loops

While...Wend loops are included in VBA for backward compatibility. In the VBA help file, Microsoft suggests that Do...Loops are more flexible. However, because you might encounter While...Wend loops in code written by others, a quick example is provided. In this loop, the first line is always While <condition>. The last line of the loop is always Wend. Note that there is no Exit While statement. In general, these loops are okay, but the Do...Loop construct is more robust and flexible. Because the Do loop offers either the While or Until qualifier, this qualifier can be used at the beginning or end of the loop, and there is the possibility to exit a Do loop early:

image

VBA Loop: For Each

Even though the VBA loop is an excellent loop, the macro recorder never records this type of loop. VBA is an object-oriented language. It is common to have a collection of objects in Excel such as a collection of worksheets in a workbook, cells in a range, pivot tables on a worksheet, or data series on a chart.

This special type of loop is great for looping through all the items in the collection. However, before discussing this loop in detail, you need to understand a special kind of variable called object variables.

Object Variables

At this point, you have seen a variable that contains a single value. When you have a variable such as TotalSales = 0, TotalSales is a normal variable and generally contains only a single value. It is also possible to have a more powerful variable called an object variable that holds many values. In other words, any property associated with the object is also associated with the object variable.

Generally, developers do not take the time to declare variables. Many books implore you to use the DIM statement to identify all your variables at the top of the procedure. This allows you to specify that a certain variable be of a certain type, such as Integer or Double. Although this saves a tiny bit of memory, it requires you to know up front which variables you plan on using. However, developers tend to whip up a new variable on-the-fly as the need arises. Even so, there are great benefits to declaring object variables. For example, the VBA AutoComplete feature turns on if you declare an object variable at the top of your procedure. The following lines of code declare three object variables: a worksheet, range, and a pivot table:

image

In this code, you can see that more than an equals statement is used to assign object variables. You also need to use the Set statement to assign a specific object to the object variable.

There are many good reasons to use object variables, not the least of which is the fact that it can be a great shorthand notation. It is easier to have a many lines of code refer to WSD rather than ThisWorkbook.Worksheets("Data"). In addition, as mentioned earlier, the object variable inherits all the properties of the object to which it refers.

The For Each...Loop employs an object variable rather than a Counter variable. The following code loops through all the cells in Column A. The code uses the .CurrentRegion property to define the current region and then uses the .Resize property to limit the selected range to a single column. The object variable is called Cell. Any name could be used for the object variable, but Cell seems more appropriate than does something arbitrary like Fred.

image

This code sample searches all open workbooks, looking for a workbook where the first worksheet is called Menu:

image

In this code sample, all shapes on the current worksheet are deleted:

For Each Sh in ActiveSheet.Shapes
    Sh.Delete
Next Sh

This code sample deletes all pivot tables on the current sheet:

For Each pt in ActiveSheet.PivotTables
    pt.TableRange2.Clear
Next pt

Note that Application.PathSeparator is a backslash on Windows computers but might be different if the code is running on a Macintosh.

Flow Control: Using If...Then...Else and Select Case

Another aspect of programming that will never be recorded by the macro recorder is the concept of flow control. Sometimes you do not want every line of your program to be executed every time you run the macro. VBA offers two excellent choices for flow control: the If...Then...Else construct and the Select Case construct.

Basic Flow Control: If...Then...Else

The most common device for program flow control is the If statement. For example, suppose you have a list of products as shown in Figure 5.11. You want to loop through each product in the list and copy it to either a Fruits list or Vegetables list. Beginning programmers might be tempted to loop through the rows twice—once to look for fruit and a second time to look for vegetables. However, there is no need to loop through twice because you can use an If...Then...Else construct on a single loop to copy each row to the correct place.

image

Figure 5.11. A single loop can look for fruits or vegetables.

Conditions

Any If statement needs a condition that is being tested. The condition should always evaluate to TRUE or FALSE. Here are some examples of simple and complex conditions:

If Range("A1").Value = "Title" Then

If Not Range("A1").Value = "Title" Then

If Range("A1").Value = "Title" And Range("B1").Value = "Fruit" Then

If Range("A1").Value = "Title" Or Range("B1").Value = "Fruit" Then

If...Then...End If

After the If statement, you may include one or more program lines that will be executed only if the condition is met. You should then close the If block with an End If line. Here is a simple example of an If statement:

image

Either/Or Decisions: If...Then...Else...End If

Sometimes you will want to do one set of statements if the condition is true, and another set of statements if the condition is not true. To do this with VBA, the second set of conditions would be coded after the Else statement. There is still only one End If statement associated with this construct. For example, you could use the following code if you want to color the fruit red and the vegetables green:

image

Using If...Else If...End If for Multiple Conditions

Notice that our product list includes one item that is classified as an herb. You have three conditions that can be used to test items on the list. It is possible to build an If...End If structure with multiple conditions. First, test to see whether the record is a fruit. Next, use an Else If to test whether the record is a vegetable. Then, test to see whether the record is an herb. Finally, if the record is none of those, highlight the record as an error.

image

Using Select Case...End Select for Multiple Conditions

When you have many different conditions, it becomes unwieldy to use many Else If statements. For this reason, VBA offers another construct known as the Select Case construct. In your running example, always check the value of the Class in column A. This value is called the test expression. The basic syntax of this construct starts with the words Select Case followed by the test expression:

Select Case Cells(i, 1).Value

Thinking about this problem in English, you might say, “In cases where the record is fruit, color the record with red.” VBA uses a shorthand version of this. You write the word Case followed by the literal "Fruit". Any statements that follow Case "Fruit" will be executed whenever the test expression is a fruit. After these statements, you have the next Case statement: Case "Vegetables". You continue in this fashion, writing a Case statement followed by the program lines that will be executed if that case is true.

After you have listed all the possible conditions you can think of, you may optionally include a Case Else section at the end. The Case Else section includes what the program should do if the test expression matches none of your cases. Finally, close the entire construct with the End Select statement.

The following program does the same operation as the previous macro but uses a Select Case statement:

image

Complex Expressions in Case Statements

It is possible to have fairly complex expressions in Case statements. You might want to perform the same actions for all berry records:

Case "Strawberry", "Blueberry", "Raspberry"
     AdCode = 1

If it makes sense, you might code a range of values in the Case statement:

Case 1 to 20
    Discount = 0.05
Case 21 to 100
    Discount = 0.1

You can include the keyword Is and a comparison operator, such as > or <:

Case Is < 10
    Discount = 0
Case Is > 100
    Discount = 0.2
Case Else
    Discount = 0.10

Nesting If Statements

It is not only possible, but also common to nest an If statement inside another If statement. In this situation, it is important to use proper indenting. You will often find that you have several End If lines at the end of the construct. By having proper indenting, it is easier to tell which End If is associated with a particular If.

The final macro has a lot of logic. Our discount rules are as follows:

• For Fruit, quantities under 5 cases get no discount.

• Quantities from 5 to 20 cases get a 10 percent discount.

• Quantities above 20 cases get a 15 percent discount.

• For Herbs, quantities under 10 cases get no discount.

• Quantities from 10 cases to 15 cases get a 3 percent discount.

• Quantities above 15 cases get a 6 percent discount.

• For Vegetables except Asparagus, 5 cases and above earn a 12 percent discount.

• Asparagus requires 20 cases for a discount of 12 percent.

• None of the discounts applies if the product is on sale this week. The sale price is 25 percent off the normal price. This week’s sale items are Strawberry, Lettuce, and Tomatoes.

The code to execute this logic follows:

image

image

Next Steps

Loops add a tremendous amount of power to your recorded macros. Any time you need to repeat a process over all worksheets or all rows in a worksheet, a loop is the way to go. Excel VBA supports the traditional programming loops of For...Next and Do...Loop and the object-oriented loop of For Each...Next. Next, Chapter 6, “R1C1-Style Formulas,” discusses the seemingly arcane R1C1 style of formulas and shows why it is important in Excel VBA.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset