Skip to the Next Iteration of a Loop
The Visual Basic language provides a handful of common
flow control statements, which let you direct the
execution of your code. For example, you can use Return to step out of a function, or Exit to back out of a loop. However, before VB
2005, there wasn't any way to skip to the next iteration of a
loop.
Note
VB's new Continue keyword gives you a quick way to step out of a tangled block of code in a loop and head straight into the next iteration.
How do I do that?
The Continue statement is one
of those language details that seems like a minor frill at first, but
quickly proves itself to be a major convenience. The Continue statement exists in three versions:
Continue For, Continue Do, and Continue While, each of which is used with a
different type of loop (For ...
Next, Do ... Loop, or While ... End
While).
To see how the Continue
statement works consider the following code:
For i = 1 to 1000
If i Mod 5 = 0 Then
' (Task A code.)
Continue For
End If
' (Task B code.)
NextThis code loops 1,000 times, incrementing a counter i. Whenever i is divisible by five, the task A code
executes. Then, the Continue For
statement is executed, the counter is incremented, and execution
resumes at the beginning of the loop, skipping the code in task
B.
In this example, the continue statement isn't really required, because you could rewrite the code easily enough as follows:
For i = 1 to 1000
If i Mod 5 = 0 Then
' (Task A code.)
Else
' (Task B code.)
End If
NextHowever, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access