Visual Basic includes three major types of loops: For . . . Next, For Each . . . Next, and Do . . . Loop. Just as conditions allow you to break up the sequential monotony of your code through branches, loops add to the usefulness of your code by letting you repeat a specific block of logic a fixed or variable number of times. For . . . Next LoopsThe most common loop structure is the For . . . Next loop. This loop uses a numeric counter that increments from a starting value to an ending value, processing the code within the loop once for each incremented value. Dim whichMonth As Integer For whichMonth = 1 To 12 ProcessMonthlyData(whichMonth) Next counter This sample loops 12 times (1 to 12), once for each month. You can specify any starting and ending values you wish; this range can also be specified using variables or functions that return numeric values. Once the starting and ending values are obtained, they are not recalculated each time through the loop, even if a function call is used to obtain one or both limits. ' ----- Month(Today) returns the numeric month ' for the current date. For whichMonth = 1 To Month(Today) ProcessMonthlyData(whichMonth) Next counter Normally, the loop increments by one (1) each time through. You can alter this default by attaching a Step clause to the end of the For statement line. For countDown = 60 To 0 Step -1 ... Next countDown One additional syntax variation allows you to declare the loop counter variable within the statement itself. Such variables are available only within the loop, and cease to exist once the loop exits. For whichMonth As Integer = 1 To 12 ProcessMonthlyData(whichMonth) Next whichMonth For Each . . . Next LoopsA variation of the For loop, the For Each . . . Next loop, scans through a set of ordered and related items, from the first item until the last. Arrays and collection objects also work, as does any object that supports the IEnumerable interface (all these topics are covered in Chapter 6). The syntax is quite similar to the standard For statement. For Each oneRecord In setOfRecords ProcessRecord(oneRecord) Next oneRecord Do . . . Loop LoopsSometimes you want to repeat a block of code as long as a certain condition is true, or only until a condition is true. The Do . . . Loop structure performs both of these tasks. The statement includes a While or Until clause that specifies the conditions for continued loop processing. For instance, the following statement does some processing for a set of dates, from a starting date to an ending date. Dim processDate As Date = #1/1/2000# Do While (processDate < #2/1/2000#) ' ----- Perform processing for the current date. ProcessContent(processDate) ' ----- Move ahead to the next date. processDate.AddDays(1) Loop Processing in this sample will continue until the processDate variable exceeds 2/1/2000, which indicates the end of processing. The Until clause version is somewhat similar, although with a reversed condition result. Do Until (processDate >= #2/1/2000#) ... Loop Make the included condition as simple or as complex as you need. Putting the Until or While clause at the bottom of the loop guarantees that the statements inside of the loop will always be processed at least once. Do ... Loop Until (processDate >= #2/1/2000#) There is another loop that is similar to Do . . . Loop called the While . . . End While loop. However, it exists for backward compatibility only. Use the Do . . . Loop statement instead. Exit StatementsNormally, when you enter a loop, you have every intention of looping for the full number of times specified by the initial conditions of the loop. For For loops, you expect to continue through the entire numeric range or collection of elements. In Do loops, you plan to keep the loop going as long as the exiting condition has not yet been met. But there may be loops that you want to exit early. You accomplish this using an Exit statement. There are two loop-specific exit statements.
Each Exit statement exits the loop that contains the statement; processing continues with the line immediately following the loop. For whichMonth = 1 To 12 If (ProcessMonthlyData(whichMonth) = False) Then Exit For Next whichMonth ' ----- Code continues here no matter how the loop was exited. The following sample is designed to loop through all 12 months. However, a processing failure for any of the 12 months will immediately exit the loop, abandoning all remaining month processing actions. The Exit Do statement similarly exits Do . . . Loop loops immediately. When using an Exit loop statement within nested loops (where one loop appears within another), only the matching loop that immediately contains the statement is exited. For whichMonth = 1 To 12 For whichDay = 1 to DaysInMonth(whichMonth) If (ProcessDailyData(whichMonth, whichDay) = False) _ Then Exit For Next whichDay ' ----- The Exit For statement jumps to this line. ' Processing continues with the next month. Next whichMonth Continue StatementsBecause exiting a loop abandons all remaining passes through the loop, you may miss out on importing processing that would have happened in subsequent passes. Visual Basic includes a Continue statement that lets you abandon only the current pass through the loop. There are different Continue statement variations for each of the loop types.
Because the loop conditions are reevaluated when using the Continue statements, there are times when Continue may cause the loop to exit, such as when it had been the final pass through the loop already. In this example, the Continue For statement skips processing for months that have no data to process. For whichMonth = 1 To 12 If (DataAvailable(whichMonth) = False) The Continue For RetrieveData(whichMonth) ProcessData(whichMonth) SaveData(whichMonth) Next whichMonth |