You can place, or nest, control structures inside other control structures (such as an If… Then block within a For … Next loop). Control structures in Visual Basic can be nested in as many levels as you want. It’s common practice to indent the bodies of nested decision and loop structures to make the program easier to read. Here is the structure of a nested For … Next loop that scans all the elements” of a two-dimensional array:
The outer loop (with the irow counter) scans each row of the array, and the inner loop scans each column. The outer loop scans each element in the first row of-the array, the elements of the second row, and so on, until the entire array has been scanned. The loop’s body can process the element Array2/irow, icol).
You can also nest control flow structures. The following structure tests a user supplied value to determine if it’s positive and, if so, determines whether the value exceeds a certain limit:
The Income variable is first compared with zero. If it’s negative, the Else clause of the U… Then statement is executed-If it’s positive, it’s compared with the value 20000, and depending on the outcome, a different message is displayed.
The Exit Statement
The Exit statement allows you to exit prematurely from a block of statements in a control structure, from a loop, or even from a procedure. Suppose you have a For … Next loop that calculates the square root of a ~es of numbers. Because the square root of negative numbers can’t be calculated (the Sqr() function generates a runtime error), you might want to.halt the operation if the array contains an invalid value. To exit the loop prematurely, use the Exit For statement as follows:
If a negative element is found in this loop, the program exits.the loop and continues with the statement following the Next statement.
There are similar Exit statements for the Do loop (Exit Do), as well as for functions and subroutines (Exit Function and Exit Subroutine). If the previous loop was part of a function, you might want to assign an error code to the function and exit not only the loop” but the function itself:
If this code is part of a subroutine procedure, you use the Exit Subroutine statement. The Exit statements for loops are Exit For and Exit Do. There is no way (or compelling reason) to exit prematurely from an If or Case statement. There is also an Exit Property statement, which we’ll look at in Chapter 16, Building Active Controls .