For Next Loop

The For.. .Next loop is used when you know how many times you want to repeat a group of statements. The syntax of a For.. .Next loop looks like this:

For counter = start To end [Step increment] statement1 statement2 statementN Next [counter]

The code in the brackets is optional. Counter is a numeric variable that stores the number of iterations. Start is the number at which you want to begin counting. End indicates how many times the loop should be executed. For example, if you want to repeat the statements inside the loop five times, use the following For statement:

For counter = 1 To 5 statements


When Visual Basic encounters the Next statement, it will go back to the beginning of the loop and execute the statements inside the loop again, as long as the counter hasn't reached the end value. As soon as the value of counter is greater than the number entered after the To keyword, Visual Basic exits the loop. Because the variable counter automatically changes after each execution of the loop, sooner or later the value stored in counter exceeds the value specified in end.

By default, every time Visual Basic executes the statements inside the loop, the value of the variable counter is increased by one. You can change this default setting by using the Step clause.

For example, to increase the variable counter by three, use the following statement:

For counter = 1 To 5 Step 3

statements Next counter

Introduction to Access 2003 VBA Programming

When Visual Basic encounters the above statement, it executes the statements inside the loop twice. The first time the loop runs the counter equals 1. The second time in the loop, the counter equals 4 (3+1). After the second time inside the loop, the counter equals 7 (4+3). This causes Visual Basic to exit the loop.

Note that the Step increment is optional. Optional statements are always shown in square brackets (see the syntax at the beginning of this section). The Step increment isn't specified unless it's a value other than 1. You can place a negative number after Step. Visual Basic will then decrement this value from the counter each time it encounters the Next statement. The name of the variable (counter) after the Next statement is also optional; however, it's good programming practice to make your Next statements explicit by including counter.

How can you use the For.. .Next loop in Microsoft Access? Suppose you want to get the names of the text boxes located on an active form. The procedure in the next hands-on demonstrates how to determine if a control is a text box and how to display its name if a text box is found.

0 0

Post a comment