Loop statements allow you to execute one or more lines of code repetitively. Many tasks consist of trivial operations that must be repeated over and over again, and looping structures are an important part of any programming language. Visual Basic supports the following loop statements:
- Do Loop
- For Next
- While … Wend
Do… Loop
The Do … Loop executes a block of statements for as long as a condition is True. Visual Basic evaluates an expression, and if it’s True, the statements are execute If the expression is-False, the program continues and the statement following the loop is executed.
There are two variations of the Do..Loop statement and.both Use the same ba model. A loop can be executed either while the condition is True or until the Condition becomes True. These two variations use the keywords While and Until to specific If- how long the statements are executed. To execute a block of statements while a condition is True, use the following syntax:
Do While condition
statement-block
Loop
To execute a block of statements until the condition becomes True, use the following syntax:
Do Until condition
statement-block
Loop
When Visual Basic executes the previous loops, it first evaluates condition. If condition is False, the Do … While or Do… Until loop is skipped (the statements aren’t even executed once). When the Loop statement is reached, Visual Basic evaluates the expression again and repeats the statement block of the Do… While loop if the expression is True, or repeats the statements of the Do … Until loop if the expression is False.
The Do … Loop can execute any number of times as long as condition is True (or nonzero if the condition evaluates to a number).,Moreover, the number of iterations need not be known before the loops starts. If condition is initially False, the statements may never execute.
Here’s a typical example of using a Do … Loop. Suppose the string MyText holds a piece of text (perhaps the Text-property of a TextBox control), and you want to count the words in the text. (We’ll assume that there are no multiple spaces in the text and that the space character separates successive words.) To locate an instance of a character in a string, use the InStr() function, which accepts three arguments:
- The starting location of the search
- The text to be searched
- The character being searched .
The following loop repeats for as long as there are spaces in the text. Each time the InStr() function finds another space in the text, it returns the location (a positive number) of the space. When there are no more spaces in the text, the InStr() function returns zero, which signals the end of the loop, as shown.
The Do… Loop is executed while the InStr() function returns a positive number, which happens for as long as there are more words in the text. The variable position holds the location of each successive space character in the text. The search for the next space starts at the location of the current space plus 1 (so that the program won’t keep finding the same space). For each space found, the program increments the value of the words variable, which holds the total number of words when the loop ends.
You may notice a problem with the previous code segment. It assumes that the text contains at least one word and starts by setting the position variable to 1. If the MyText variable contains an empty string, the program reports that it contains one word. To fix this problem, you must specify the condition as follows:
The line words = words + 1 is necessary because the last word is not delimited by a space.
This code segment counts the number of words correctly, even if the MyText variable contains an empty string. If the MyText String variable doesn’t contain any spaces, the function InStr() position + 1, MyText, ” “) returns 0, which corresponds to False, and the Do loop isn’t executed:
You can code the same routine with the until, keyword. In this case, you must continue to search for spaces until position becomes zero. Here’s the same code with a different loop (the InStr() function returns 0 if the string it searches for doesn’t exist in the longer string):
Another variation of the Do loop executes the statements first and evaluates the Condition after each execution: This Do loop has the following syntax:
Do·
statements
Loop While condition
or
Do
statements
Loop Until condition
The statements in this type of loop execute at least once, since the condition is examined at the end of the loop.
Could we have implemented the previous example with one of the last two types of loops? The fact that we had to do something special about zero-length strings suggests that this problem shouldn’t be coded with a loop that tests the condition at the end. Since the loops’ body will be executed once, the words variable is never,going to be zero.
As you can see, you can code loops in a number of ways with the Do … Loop ‘statement, and the way you use it will depends on the problem at hand and your programming style.
Of course, text is not made up of words. seperated by single spaces. You may have multiple spaces between words, tabs, and multiple lines of text. The WCount application in this chapter’s folder on the CD counts words with a more robust procedure. You can open the project and examine its code, which is thoroughly documented.
For…Next
The For… Next loop is one of the oldest loop structures in programming Ianguages. Unlike the Do loop, the For … Next loop requires that you know how many times the statements in the loop will be executed. The For … Next loop uses a variable (it’s called the loop’s counter) that increases or decreases in value during each repetition of the loop. The For … Next loop has the following syntax:
For counter = start To end [Step increment]
statements
Next [counter]
The keywords in the square brackets are optional. The arguments counter, start, end, and increment are all numeric, The loop is executed as many times as required for the Counter to reach (or exceed) the end value.
In executing a For … Next loop, Visual Basic completes the following steps:
- Sets counter equal to start
- Tests to see if counter is greater than end. If so, it exits the loop. If increment is negative, Visual Basic tests to see if counter is less than end. If it is, it exits the loop.
- Executes the statements..in the block
- Increments counter by the amount specified with the increment argument. If the increment argument isn’t specified, counter is incremented by 1.
- Repeats the statements
The following For … Next loop scans all the elements of the numeric array data and calculates their average:
For i = 0 To UBound(data)
total = total + data(i)
Next i
Debug.Print total / UBound(a)
The single most important thing to keep in mind when working with For … Next loops is that the loop’s counter is set at the beginning of the loop. Changing the value of the end variable in the loop’s body-Won’t have any effect. For example, the following loop will be executed 10 times, not 100 times:
endValue = 10
For i = 0 To endValue
endValue = 100
(more statements)
Next i
You can, however; adjust the value of the counter from within the loop. The following is an example ,of an endless (or infinite) loop:
For i = 0 To 10
Debug.Print i
i = i = 1
Next i
This loop never ends because the loop’s Counter, in effect, is never increased. (If you try this, press Control+Break to interrupt the endless loop.)
The increment argument can be either positive or negative. If start is greater than end, the value of increment must be negative. If not, the loop’s body won’t be executed, not even once.
Finally, the counter variable need not be listed after the Next statement, but it makes the code easier to read, especially when For … Next loops are nested within each other (nested loops are discussed. in the section “Nested Control Structures” later in the chapter).
While …Wend
The While …Wend loop executes a block of statements while a condition is True. The While … Wend loop has the following syntax.
While condition
statement-block
Wend
If condition is True, all statements are executed and when the Wend statement is reached, control is returned to the While statement which evaluates condition again. If condition is still True, the process is repeated. If condition is False, the program resumes with the statement following the Wend statement:
The following While …Wend loop prompts the user for numeric data. The user can type a negative value to indicate that all values are entered:
.
You assign the value 0 to the number variable before the loop starts because this value can’t “affect the total. Another technique is to precede the While statement with an InputBox function to get the first number from the user.