Skipping in For Loops (Continue)
In VBA, it is common to use For loops for iterative processing. However, there may be cases where you want to skip the remaining part of the loop and move on to the next iteration under certain conditions.
In this article, we will show you how to use the GoTo statement to skip to the next iteration in a For loop.
How to Skip to the Next Iteration in a For Loop
To skip to the next iteration in a For loop, you can use the GoTo statement.
The GoTo statement is used to jump to a specified label. Since VBA does not have a Continue
statement, you can use the GoTo statement to set a label just before the end of the For loop and jump to that label using the GoTo statement to skip to the next iteration.
The following VBA code example loops through numbers from 1 to 10, prints the number to the log if it is odd, and skips to the next iteration if it is even.
Public Sub ForLoopWithGoTo()
Dim i As Integer
For i = 1 To 10
If i Mod 2 = 0 Then ' If the number is even
GoTo NextIteration ' Skip to the next iteration
End If
Debug.Print i ' If the number is odd, print the number to the log
NextIteration:
Next i
End Sub
In this code, if the condition If i Mod 2 = 0 Then
is met (i.e., if i is even), the GoTo NextIteration
command jumps to the label NextIteration:
and proceeds to the next iteration of the For
loop.
By setting any desired condition in the IF
statement in the sample code, you can skip to the next loop under any condition.
About the GoTo Command
The GoTo
command is used to jump the program flow to a specified label position.
A label is any name followed by a colon (:) that indicates a specific position in the code.
For more information about the GoTo command, refer to this article.
Considerations when using the GoTo Command
The GoTo
command is deprecated or not implemented in many programming languages today.
This is because the GoTo
command can make the program flow opaque and make the code harder to read.
Also, labels are only valid within the same procedure and cannot be jumped to in a different procedure or module.
Abusing the GoTo command can decrease the maintainability of the program, so it is recommended to write code using control structures (such as If-Then-Else, Select Case) as much as possible.
The use of the GoTo
command in this For
loop is to be understood as an exceptional use case to skip the loop under specific conditions.
Summary
In VBA, you can skip to the next iteration in a For loop by using the GoTo command.
However, considering the readability and maintainability of the program, it is recommended to use the GoTo command only when necessary.
It is important to make the program logic clear and strive for better code.