Recipe 6.9. Declaring Loop Counters Within Loops


You want to create a variable to hold the loop counter in a For…Next loop, but you want the variable to exist only within the body of the loop.


Declare the variable type directly using the optional syntax for doing this in the For… Next loop command.


If you include As Type immediately after the variable name used in the For…Next statement, Visual Basic 2005 creates this variable on the spot, and its scope is limited to the body of the For…Next loop. If you declare the variable elsewhere, don't add the As Type clause in the loop statement; doing so triggers an exception.

This sample code creates nested For…Next loops, with the outer loop counter variable declared outside the loop and the inner loop variable declared just for the body of the loop. Study the lines starting with For to see the difference:

 Dim formatString As String = "outerLoop: {0} innerLoop: {1} "Dim result As String = "" Dim outerLoop As Integer For outerLoop = 1 To 2    For innerLoop As Integer = 1 To 2       result &= String.Format(formatString, _          outerLoop, innerLoop)       result &= vbNewLine    Next innerLoop Next outerLoop MsgBox(result) 

These two loops are nearly the same. Their counter variable values are displayed each time through the inner loop, as shown in Figure 6-9. The variable outerLoop can be referenced past the end of the sample lines of code, but referencing innerLoop will causes an exception. innerLoop exists only within the For…Next loop where it is declared.

Figure 6-9. The results of our nested loops using two different counter declaration methods

See Also

See "For…Next statements" in Visual Studio Help for more information.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: