During this hour you will learn
This hour describes how your Visual Basic programs can continually execute the same set of instructions. When Visual Basic executes the same instructions over and over, Visual Basic is looping. A loop is a series of statements that execute repeatedly. Many times you have to repeat a calculation or print the same message several times.
Visual Basic supports several kinds of loop statements. The looping statements all repeat a section of Visual Basic code until a certain condition is met.
This topic section introduces the Visual Basic loop statements called the Do...Loop loops. There are four different kinds of Do...Loops. In most cases, the Do...Loop you select depends more on your preference and not on coding requirements, because you can write almost any loop by using any of the looping statements.
FAST TRACK |
Have you programmed in QBasic or Access Basic? If so, you've already mastered Visual Basic's looping statements. Skip to Hour 12's lesson to learn how Visual Basic supports array handling. |
This topic introduces the following kinds of loop statements:
Actually, the first four statements in this list are just specific versions of the more generalized Do...Loop statement. The placement of the While and Until determines how the loop behaves.
Some desired program repetition just isn't possible without loops. Suppose that you ask users whether they want a report sent to the screen or to the printer by displaying Figure 11.1's dialog box. If users doesn't press an S or a P, you probably want to tell them that you don't recognize the answer and then repeat the question. In fact, you have to keep asking the same question over and over until the users answer with something that you're expecting. The loop of statements, therefore, contains the InputBox() to ask the question, an If statement to check the answer, and a MsgBox() to issue an error message so users know what's going on.
Users should answer by pressing either S or P.
You often write procedures that loop because your procedures are processing sets of data values many times. As you add loops to your programs, you need to guard against writing endless loops. A never-ending procedure is no more useful to you than one that doesn't work correctly in the first place. With an endless loop, your users can never regain control of the machine.
Before you go further, you should learn what to do if you happen to write a procedure with an endless loop. In Visual Basic (as with most dialects of BASIC), you can stop a procedure in mid-execution by pressing Ctrl+Break. The procedure then stops, and you return to the Code window so that you can edit the program.
![]()
The General Do...Loop Statement
One of the most common ways to perform a loop in Visual Basic is to use the Do...Loop statement. Do...Loop has several syntaxes. Your choice of syntaxes has more to do with your own preference and style than with programming requirements. Because the many syntaxes can get confusing, this section presents all the Do...Loop syntaxes for your perusal; the following sections explain each one. The syntaxes of the Do...Loop statement are as follows:
Do While condition Block of one or more Visual Basic statements Loop Do Block of one or more Visual Basic statements Loop While condition Do Until condition Block of one or more Visual Basic statements Loop Do Block of one or more Visual Basic statements Loop Until condition
Indent the inner statements of loops so that you can spot the statements easily inside the loop.
![]()
The condition is a comparison, Is...() function, or any other VB language element that returns a True or False data type result. As with the If statement's comparison, any non-zero value is true, and a zero value is always false. Therefore, the condition might be nothing more than a numeric variable or control.
Figure 11.2 gives you an overview of Do...Loop's action within a procedure. The arrow shows you how the Do...Loop repeats a section of the procedure. Until this hour's lesson, all procedures that you've seen have flowed sequentially from top to bottom without any repetition.
The Do...Loop repeats a section of code.
The While keyword causes Visual Basic to repeat the loop as long as (while) the condition is true. The Until keyword causes Visual Basic to repeat the loop as long as the condition is false (until the condition becomes true).
![]()
All loops supply ways to control the statements executing through conditional tests. The loops' conditional tests use the same comparison operators you saw in Hour 10 with the If statement (refer to Hour 8's lesson for a review of the comparison operators).
If you look at the formats for the Do loops, you see that the condition resides at either the top of the loop or at the bottom. The placement of the conditional test determines how the Do loop terminates its repetition. Remember to guard against endless loops. You must have some way of quitting every loop you put in your programs; the condition is the way to end the loop. Basically, the While condition keeps the loop repeating as long as the relation is true, but as soon as the relation becomes false, Visual Basic quits repeating the loop and finishes the procedure following the Loop statement.
Listing 11.1 show a Do While...Loop sample code fragment that tests its relation at the top of the loop.
Listing 11.1 Docount1.bas: Counting with a Do While...Loop
Dim intCount As Integer Dim msg As Integer ' MsgBox() return intCount = 1 Do While (intCount <= 10) ' Count up from 1 msg = MsgBox("Counting at " & intCount) intCount = intCount + 1 Loop mag = MsgBox("All done now.")
If you run a procedure with this code, you'll see message boxes that display the following output:
Counting at 1 Counting at 2 Counting at 3 Counting at 4 Counting at 5 Counting at 6 Counting at 7 Counting at 8 Counting at 9 Counting at 10 All done now.
intCount is the variable being tested. As long as the value of intCount is less than or equal to 10, the body of the loop executes. The body of the loop executes over and over until the value of intCount is greater than 10. The only way the loop stops executing (and thereby not becoming an endless loop) is that the body of the loop must change intCount.
The statement intCount = intCount + 1 is called a counter statement, not because the variable is named intCount, but because the same variable appears on both sides of the equal sign. When you see the same variable name on both sides of an equal sign, the variable is being changed. One is being added to intCount every time your computer executes the statement intCount = intCount + 1. (Remember that the assignment statement evaluates whatever is to the right of the equal sign first and then stores that value into the variable on the left.) Every time the body of the loop executes, intCount is changed. Eventually, intCount will be more than 10, and the loop will stop looping.
A counter statement can also count down by subtracting one from a counter variable each time through a loop-for example, intCount = intCount - 1.
![]()
intCount begins at 1. The Do While...Loop continues until intCount is more than 10. Because the loop tests the condition at the top of the loop, as soon as intCount becomes 11, the loop stops and any code that follows the Loop statement continues then. The loop you saw earlier prints the message 10 times. On the 11th iteration (another name for loop), the condition becomes false and the loop then ends.
The primary difference between the Do While...Loop and the Do...Loop While is the placement of the conditional test.
Listing 11.2 shows the same code as shown in Listing 11.1, with its conditional While test at the bottom of the loop.
Listing 11.2 Docount2.bas: Counting with Do...Loop While
Dim intCount As Integer Dim msg As Integer ' MsgBox() return intCount = 1 Do msg = MsgBox("Counting at " & intCount) ' Print in the message box intCount = intCount + 1 Loop While (intCount <= 10) msg = MsgBox("All done now.")
The body of this loop continues as long as intCount is less than or equal to 10. The conditional test is located at the bottom of the loop. Therefore, when intCount is more than 10, the body of the loop stops looping. In other words, Listing 11.2 produces the same output as Listing 11.1 except that the last message box that displays Counting at 10 no longer appears.
The difference between the conditional test at the top or bottom boils down to only one real difference: The body of the first loop, Do While...Loop (with the test at the top), may never execute because the test might be false before the loop ever executes. The body of the second loop, Do...Loop While (with the test at the bottom), always executes at least once. Visual Basic has no idea that the conditional test is false until it performs at least one iteration of the loop.
![]()
In each of the two preceding Do loops, you learned that the condition being tested is preceded by a While. As you can see, the loop continues executing while the condition is true. If you replace While with Until, the loop continues until the condition becomes true.
The choice of loop that you use depends on the type of statements that you feel most comfortable with. You can write any loop with any of the Do loops that you've seen.
Here's a Do...Loop While that does the same work as the previous ones:
Do strAns = InputBox("Again?") Loop While (strAns = "Y")
Here is the same code using a Do...Loop Until:
Do strAns = InputBox("Again?")) Loop Until (strAns = "N")
The test being compared in each set of loops is the opposite, even though the output is identical. The first loop prints Again? while a certain condition is true, and the second prints Again? until a certain condition is true.
You also can write Do Until...Loops that test at the top, such as this one:
Do Until (strAns = "N") strAns = InputBox("Again?") Loop
The Exit Do statement provides a way for you to quit any of the Do...Loops earlier than their normal conclusion. Generally, you use an Exit Do in the body of an If statement. Therefore, you can write a loop that's controlled by the Do condition, but if an extraordinary circumstance arises (such as users entering an unexpected value inside the loop), the Exit Do statement forces Visual Basic to terminate the loop immediately and continue with the rest of the procedure, no matter how the Do condition tests.
One simple but common application of the Do While...Loop is ensuring that users enter a proper answer to what your program asks. The section of a program in Listing 11.3 is such a loop. Until users enter a yes or no answer, the program keeps prompting for a correct answer. The UCase() function converts the users' answer to uppercase to help the relational test.
Listing 11.3 Yesno.bas: Using a Loop to Get a Yes or No Answer
Dim strAns As String Dim msg As Integer ' MsgBox() return ' Section of a procedure that asks a yes or no question strAns = InputBox("Do you want to continue (yes or no)") Do While (UCase(strAns) <> "YES" And UCase(strAns) <> "NO") msg = MsgBox("You didn't answer yes or no", vbExclamation) Beep ' Ring the bell strAns = InputBox("Do you want to continue (yes or no)") Loop
In Listing 11.3, the program requires two InputBox() functions to ask for user input so that it can print the error message inside the loop.
![]()
The procedure in Listing 11.4 asks users for a number. A Do...Loop Until (which tests the relation at the bottom of the loop) beeps that number of times. Remember that Visual Basic performs an automatic numeric comparison when testing a number against a string that holds a number.
Listing 11.4 Beeploop.bas: The Do...Loop Until Controls the Beeping
' Beep at the user however many times the user wants Dim strTimes As String Dim intCount As Integer Dim msg As Integer ' MsgBox() return strTimes = InputBox("How many times do you want to hear a beep") intCount = 0 ' Initialize a count variable Do Beep intCount = intCount + 1 Loop Until (intCount = strTimes) ' VB performs numeric compare msg = MsgBox("That's all the beeps for now!")
In addition to the Do...Loop statements you learned in the preceding topic, Visual Basic also offers For...Next loops, which are perfect for repeating sections of your programs a fixed number of times. Whereas Do...Loops provide loops that iterate while or until a certain condition is true, For...Next loops iterate for a fixed number of times.
This topic section introduces the following:
In reality, you can write virtually any loop by using any of the four Do...Loops or the For...Next loop. The kind of loop you choose depends as much on style and personal preference as anything. Nevertheless, you may find that the For...Next loops generally are easier to code when you need a loop that loops a certain number of times, rather than one that loops based on a condition.
![]()
The For and Next statements always appear in pairs. If your program has one or more For statements, it also should have a Next statement following it somewhere. The For and Next statements enclose one or more Visual Basic statements that form the loop; the statements between For and Next repeat continuously a certain number of times. You, as the programmer, control the number of times the loop repeats.
The syntax of the For...Next loop is as follows:
For intCounter = intStart To intEnd [Step intIncrement] One or more Visual Basic statements go here Next [intCounter][, intCounter...]
Indent the body of a For...Next loop so that you can spot the contents of the loop easily.
intCounter is a numeric variable that you supply to help control the body of the loop (the statements between For and Next). The intCounter variable is initialized to the value of intStart before the first iteration of the loop. The intStart value is typically 1 but can be any numeric value (or variable) you specify. Every time the body of the loop repeats, the intCounter variable changes (increments or decrements) by the value of intIncrement. If you don't specify a Step value, the For statement assumes an intIncrement of 1.
The value of intEnd is a number (or variable) that controls the end of the looping process. When intCounter is greater than intEnd, Visual Basic doesn't repeat the loop but continues at the statement following Next.
The Next statement is Visual Basic's way of ending the loop-the signal to Visual Basic that the body of the For...Next loop is finished. If the intCounter variable is less than the intEnd variable, Visual Basic increments intCounter by the value of intIncrement, and the body of the loop repeats again.
Although the intCounter variable after Next is optional, most programmers specify one. The intCounter variable is the same one used at the top of the loop in the For statement.![]()
The procedure in Listing 11.5 uses a message box to show you how the For...Next loop really works. This procedure uses the intCtr variable to control the loop.
Listing 11.5 Fornext1.bas: Counting Up with For...Next
Private Sub forNext () Dim intCtr As Integer ' A local variable Dim msg As Integer ' MsgBox() return For intCtr = 1 To 10 ' intCtr starts off with 1 and ends with 10 msg = MsgBox(intCtr) Next intCtr ' End of the loop End Sub
The loop counts from 1 to 10, printing the numbers each time the count increments once more.
When the loop first begins, the intCtr variable is assigned a 1, the intStart value of the loop. Each time through the loop, intCtr is one more than the previous loop.
The procedure in Listing 11.6 contains a Do...Loop that works just like the For...Next loop in Listing 11.5. Although the loops in both listings do the same thing, the For...Next loop in Listing 11.5 provides easier syntax and requires less work on your part when a counter variable is involved.
Listing 11.6 Whilefor.bas.ext: Counting Up with Do...Loop Until
Private Sub whileFor () ' This procedure simulates the previous one Dim intCtr As Integer ' A local variable Dim msg As Integer intCtr = 1 ' You must initialize the variable Do msg = MsgBox(intCtr) intCtr = intCtr + 1 ' You must add 1 to Ctr Loop Until intCtr > 10 ' You must provide for the loop's exit End Sub
Don't confuse the loops with the If statement. The Do...Loop and For...Next statements are loops, and the If statement isn't a loop. The body of an If statement executes at most one time, whereas the body of a loop can execute many times.
![]()
A For...Next loop will never execute, even once, if the loop's ending value is less than the start value.
![]()
Visual Basic assumes an intStep value of 1 if you don't specify an intStep value. You can make the For loop increment the counter variable by any value. The procedure in Listing 11.7 displays the even numbers below 10, and then displays the odd numbers below 10. To display, specify a Step value of 2, to ensure that 2 is added to the counter variable each time the loop executes, instead of the default of 1 as in the previous example. (Also, the first section's start value is 2, not 1. If it were 1, the number 1 would print first, as it does in the odd-number section.)
Listing 11.7 Oddeven.bas: Using For...Next to Display Even and Odd Numbers
Private Sub oddEven () ' Prints the first few odd and even numbers Dim intNum As Integer Dim msg As Integer ' MsgBox() return MsgBox("Even numbers below 10 are about to appear") For intNum = 2 To 9 Step 2 ' Start at 2, the first even number msg = MsgBox(intNum) Next intNum ' End of first loop MsgBox("Odd numbers below 10 are about to appear") For intNum = 1 To 10 Step 2 msg = MsgBox(intNum) Next intNum End Sub
This program has two loops. The body of each one consists of the single MsgBox(). The first MsgBox() isn't part of either loop. If it were, the loop's title would print before each number printed.
The loop's intStep value determines just how much intNum increments each time through the loops. The first For statement is saying, "For each iteration through the loop, with intNum starting at 2, step through the loop by adding 2 to intNum each time." The second For statement is saying, "For each iteration through the loop, with intNum starting at 1, step through the loop by adding 1 to intNum each time."
So much of this night-school part uses message boxes and input boxes for I/O because the message and input boxes make great vehicles for getting and displaying data. Nevertheless, message and input boxes weren't really designed for output, but for interaction with users. You'll begin to see that such I/O gets tedious, especially when dealing with simple, repetitive loop output, as you've been doing last hour and this hour. Within a few more hours after you master a little more of the Visual Basic language, you'll learn how to generate and display scrolling lists of data on a Visual Basic form and how to print information directly on a form without using controls from the Toolbox.
![]()
The variable name after the Next keyword is optional; you don't have to specify it. Visual Basic realizes that every single For statement in your program requires a Next statement. Therefore, whenever Visual Basic encounters a Next without a variable, it already knows that Next is the conclusion to the loop started with the last For statement.
Although the Next variable is optional, good programmers recommend that you always specify one. Visual Basic doesn't require the variable name, but it makes your program clearer to those (or yourself) who have to make changes to it later.
![]()
To show that Visual Basic doesn't require a variable after Next, look at the following counting loop, which counts down from 10 to 1 and then prints a message. Visual Basic knows to match each Next with its preceding For counter variable, even though the variable name doesn't appear after Next.
For intCtr = 10 To 1 Step -1 MsgBox(intCtr) Next ' No variable name specified
If the last line of this code read
Next intCtr
the result would have been equivalent.
The preceding example helps show you the programming time and effort the For...Next loop saves. Here a simple loop that shows the time savings as well:
For i = 1 To 10 MsgBox(i*2) Next
This For...Next loop serves to shortcut the following 10 statements:
MsgBox(1*2) MsgBox(2*2) MsgBox(3*2) MsgBox(4*2) MsgBox(5*2) MsgBox(6*2) MsgBox(7*2) MsgBox(8*2) MsgBox(9*2) MsgBox(10*2)
As you can see, you can use the loop's control variables inside expressions.
Any Visual Basic statement can go inside the body of a For...Next loop-even another For...Next loop. When you put a loop within a loop, you're creating nested loops. The clock in a sporting event works like a nested loop. You might think this example is stretching an analogy a little far, but it truly works. A clock in a football game counts down from 15 minutes to 0. It counts down four times. The first countdown is a loop going from 15 to 0 (for each minute), and that loop is nested within another loop counting from 1 to 4 (for each of the four quarters).
Any time your program needs to repeat a loop more than once, use a nested loop. Figure 11.3 shows an outline of nested loops. You can think of the inside loop as looping "faster" than the outside loop. The For loop counting from 1 to 10 is the inside loop. It loops fastest because the variable In goes from 1 to 10 before the outside loop, the variable Out, finishes its first iteration. Because the outside loop doesn't repeat until the Next Out statement, the inside For loop has a chance to finish in its entirety. When the outside loop finally does iterate a second time, the inside loop starts all over again.
An outside loop controls the inner loop.
The block of code inside the innermost loop of Figure 11.3 executes a total of 40 times. The outside loop iterates four times, and the inner loop executes 10 times for each of the outer loop's counts.
Figure 11.4 shows two loops within an outside loop. Both loops execute in their entirety before the outside loop finishes its first iteration. When the outside loop starts its second iteration, the two inside loops repeat all over again.
You can nest two loops inside each other.
The blocks of code inside the innermost loops of Figure 11.4 execute a total of 40 times each. The outside loop iterates four times, and the inner loop executes 10 times for each of the outer loop's counts.
Notice the order of the Next variables in Figures 11.3 and 11.4. The inside loop always finishes, and therefore its Next must come before the outside loop's Next variable. If no variables are listed after each Next, the loops still are correct and work properly.
Figure 11.5 shows an incorrect order of Next statements. The "outside" loop finishes before the "inside" loop. This example doesn't fit the description of nested loops, and you get an error if you try to finish an outside loop before the inside loop finishes.
Be careful how you nest loops.
To sum up nested loops, follow this rule of thumb: In nested loops, the order of the Next variables should be the opposite of the For variables. This arrangement gives the inside loop (or loops) a chance to complete before the outside loop's next iteration.
The indentation of Next statements has no effect on the order they execute. Indentation serves only to make programs more readable to you and other programmers.
![]()
Nested loops become especially important later when you use them for array and matrix processing, as you'll learn in Hour 12, "Handling Large Amounts of Information with Arrays."
The procedure in Listing 11.8 contains a nested loop. The inside loop counts and prints from 1 to 4; the outside loop counts from 1 to 3. Therefore, the inside loop repeats, in its entirety, four times; the procedure prints the values 1 to 4 and does so three times.
Listing 11.8 Nested1.bas: Nesting Loops to Control Multiple Counters
Private Sub nested1 () ' Print the numbers from 1 to 4 three times using a nested loop Dim intTimes As Integer, intNum As Integer Dim msg As Integer ' MsgBox() return For intTimes = 1 To 3 ' Outside loop For intNum = 1 To 4 ' Inside loop msg = MsgBox(intNum) Next intNum Next intTimes End Sub
If you follow the procedure's output, you'll see 12 message boxes that display the following values:
1 2 3 4 1 2 3 4 1 2 3 4
The For...Next loop was designed to execute a loop a specified number of times. In rare instances, however, the For...Next loop should quit before the For's counter variable has reached its end value. You can use the Exit For statement to quit a For loop early.
The syntax of Exit For is simple:
Exit For
Although Exit For can appear by itself, it generally doesn't. Exit For almost always follows the true condition inside the body of an If test. If the Exit For appears outside an If statement, the loop always quits early, defeating the purpose of the For...Next statements.
If you nest one loop inside another, the Exit For terminates the "most active" loop-that is, the innermost loop that the Exit For resides in.
![]()
The conditional Exit For (an If followed by an Exit For) is good for missing data. When you start processing data files or large amounts of user data entry, you may expect 100 input numbers but get only 95; you can use Exit For to terminate the For...Next loop before it cycles through its 96th iteration.
![]()
The count variable can count down instead of up if you specify an intStep value with a negative amount. With a negative intStep value, the initial value assigned in the For statement must be greater than the ending value so that the loop can count down.
The procedure in Listing 11.9 counts down from 10 to 1 and then prints Blast Off! at the end of the loop. To accomplish the countdown, you must use a large beginning value (10) and a negative intStep value (-1). The For statement requests that intCnt loop from 10 to 1. Each time through the loop a -1 is added to intCnt, causing the backward counting.
Listing 11.9 Countdn.bas: Producing a Countdown to Blast Off with a Negative Step Value
Private Sub countDown () ' A procedure that counts down Dim msg As Integer ' MsgBox() return For intCnt = 10 To 1 Step -1 msg = MsgBox(intCnt) Next intCnt msg = MsgBox("Blast Off!") ' The loop is done End Sub
If you run this program, you'll see the numbers 10, 9, 8, and so on appear in the message boxes, one at a time. The final message box will display the words Blast Off!
Nested loops are so important to computing that you need to practice a bit before continuing. If the inside loop's control variable is based on the outside loop's variable, you see effects such as that shown in Listing 11.10.
Listing 11.10 Nest2.bas: Nested Loops Can Help You Analyze Variables
Private Sub nested2 () ' An inside loop controlled by the outer loop's variable ' just a practice drill to follow the variables' values Dim intOuter As Integer, intIn As Integer For intOuter = 5 To 1 Step -1 For intIn = 1 To Outer Next intIn Next intOuter End Sub
No output appears in this procedure because no code in the procedure fills up a control or uses a message or input box. Instead, the code gives you some practice "playing the computer." Table 11.1 traces the two variables intOuter and intIn through this program's execution. Sometimes you have to play computer when you're learning a new concept such as nested loops. By stepping through the program a line at a time, as though you were the computer writing down each variable's contents, you produce this table.
Table 11.1 Tracing the program's output
intOuter | intIn |
5 | 1 |
5 | 2 |
5 | 3 |
5 | 4 |
5 | 5 |
4 | 1 |
4 | 2 |
4 | 3 |
4 | 4 |
3 | 1 |
3 | 2 |
3 | 3 |
2 | 1 |
2 | 2 |
1 | 1 |
The looping statements you've seen last hour and this have been simple statements to teach the mechanics of the Visual Basic language. Now is a good time to begin merging your knowledge: forms and loops. Although this topic section only skims the surface of using loops with forms, it teaches some form fundamentals that you build on throughout the rest of this course.
A form is often known as an object. Visual Basic supports several kinds of objects, such as controls, forms, and objects that reside outside your application, such as an OLE object. (OLE stands for Object Linking and Embedding; you learn more about OLE in Hour 22's lesson.)
All your form objects comprise the Forms collection, which changes as you create and remove forms within your project. The Forms collection contains the name of every form. Therefore, frmAboutBox might be the name of one of your forms within the Forms collection. (A predefined object named Form-without the s-defines the currently open form.)
Accessing the Forms Collection
Before accessing the Forms collection, you should realize that Visual Basic lets you refer to all the forms within the Forms collection without specifying the names of the individual open forms. If you have open three forms named frmAcPay, frmAcRec, and frmAcReview, for example, the predefined object Forms contains these three forms. Each form is numbered, starting at zero, and you can refer to the forms by number instead of by name. This number, called a subscript, follows after the Forms predefined object enclosed by parentheses. Table 11.2 shows you how you can refer to the three forms by using the subscript.
Table 11.2 Referring to Three Forms by Their Subscripts
Form Name | Forms Subscript Notation |
frmAcPay | Forms(0) |
frmAcRec | Forms(1) |
frmAcReview | Forms(2) |
FAST TRACK |
Visual Basic lets you specify a specific form within a collection by using yet another notation if you know the form name. Forms![frmAcPay] refers to the form named frmAcPay inside the current collection. (Unlike statement syntaxes, these brackets are required.) You can also use parentheses to refer to a collection's form by name as follows: Forms!("frmAcPay"). |
Subscripts for Controls
You may also refer to individual controls, such as fields, inside your forms by a subscript number instead of by name. Therefore, your programs can step through all the fields in a form without having to access the fields' individual names. As you learn more about data collections (especially after the next hour's lesson, which covers arrays), you'll see additional ways to refer to groups of objects.
Suppose that a form named frmStore contains five controls: three label fields named lblStoreNum, lblStoreName, and lblStoreLoc, and two list box controls named lstStoreEmps and lstStoreMgrs. Your Visual Basic procedures can refer to each control by a subscript number, starting at 0, as shown in Table 11.3. Notice that you separate the control name from the Forms collection with an exclamation point to get an individual control within that collection.
Table 11.3 Referring to Five Form Controls by Their Subscripts
Control Name | Forms Subscript Notation |
lblStoreNum | Forms!frmStore(0) |
lblStoreName | Forms!frmStore(1) |
lstStoreLoc | Forms!frmStore(2) |
lstStoreEmps | Forms!frmStore(3) |
lstStoreMgrs | Forms!frmStore(4) |
Don't confuse the subscripts used with specific form names with those in a Forms collection. If Forms precedes the subscript, the subscript refers to a particular form or subform. If the form name appears before the subscript, as seen in Table 11.3, the subscript refers to a control on that form.
![]()
Controls have properties, as you know, and so do collections. The Count property is available to you when you need to work with the Forms collection. Count simplifies your programming so that you don't have to know how many individual forms reside in the collection. By using Count, you can write generalized procedures that work on all the forms now open.
The Count property always contains an integer.
Count also contains the number of controls on a form if you apply the property to a specify form name, such as frmAcPay.Count, which contains the number of controls on the form named frmAcPay. Count includes hidden and visible controls.
![]()
The following code declares an integer variable, intC, and then stores the number of open forms in intC:
Dim intC As Integer intC = Forms.Count ' Save the number of open forms
If you want to know the number of controls on a specific form, you can use the Count property as well. The following code declares an integer variable, intCC, and stores the number of controls on the form named MyForm in intCC:.
Dim intCC As Integer intCC = MyForm.Count ' Save the number of controls on the form
A For...Next loop is the perfect tool for stepping through all the open forms in the current project. Always remember to start the controlling loop with a beginning value of 0, as done here, because 0 is the subscript of the first form.
The following code steps through all the open forms and hides the forms:
For intI = 0 To Forms.Count - 1 Forms(intI).Visible = False ' Hide each form Next intI
You may want to hide all forms when performing a system task that requires no user I/O. After your work is done, you can then repeat the loop and set each form's Visible property to True.
Visual Basic supports a special For...Next loop called the For Each...Next loop, which steps through a collection without requiring that you control a loop variable. Here is identical code that hides all the open forms:
Dim varFrmObj As Variant For Each varFrmObj In Forms varFrmObj.Visible = False ' Hide each form Next
The only loop variable you need to declare for the For Each...Next loop is a Variant variable that holds each form name as the loop iterates through the forms in the collection. In the same manner, the following For Each loop's first statement sets up a loop that steps through every control on the form named frmMyForm:
For Each varControl In frmMyForm
After you learn to write looping control statements, you can repeat sections of code over and over. Without loops, you have to write the same code back to back; even if you do that, some loops iterate (a fancy term for repeat) several thousand times, depending on the amount of data being manipulated.
Throughout this section of the book, you learn about several loop constructions. The first presented in this hour's first topic are Do...Loops, of which there are four kinds. They center around the While and the Until keywords. The location of the conditional test determines how the loops behave; if the test is at the top of the loop, the loop may never execute because the condition might be false to begin with. If the test is at the bottom of the loop, the loop always executes at least one time.
The For...Next loop allow you to control a loop when you know how many iterations are supposed to be performed. Although you can write Do...Loops to behave exactly like For...Next loops (and the reverse is true as well), For...Next loops reduce the amount of coding you have to do when you iterate through loops by using control variables that count up or down. By changing the value of the Step option, you can force the For...Next loop to count up or down by any increment or decrement you want. If you don't specify a Step value, the For...Next loop assumes a Step value of 1.
You can nest For...Next loops so that an outer loop can control one or more inner loops. Any statement can appear in the body of a For...Next loop, including Do...Loops. Toward the end of this lesson, you learned about combining For...Next loops with subscripted form names and controls. By using the For...Next, you can work with forms and controls without having to refer to each of them by name.
In Hour 12 you learn how to declare a large amount of variable storage that you'll often use in programs that process numerous data values.
intCounter = intCounter + 1
intN = 0 Do While (intN > 0) intN = intN + 3 msg = MsgBox("**") Loop
intN = 10 Do msg = MsgBox("**") Loop Until (intN > 100)
For intC = 1 To 5 Beep Next intC
For intOut = 1 To 3 For intIn = 1 To 10 MsgBox(intIn) Next intOut Next intIn