Array Class Collections File String Console Data Directive Enum Exception If Interface Lambda Loop Nothing Number Process Property Regex Sort StringBuilder Structure Sub Time Windows
A loop executes statements repeatedly. It often has an upper and lower bound. The For-loop proceeds through a range of values. A step indicates the progression. Other loops, such as While, continue until a condition is met.
Here are the looping constructs in the VB.NET language. The For Each construct is probably the least error-prone but is not always available. We also show examples of the For-loop construct directly on this page.For Each While Do While Do Until
This example uses the lower bound 0 and the upper bound 5 in the For-loop statement. Please remember that the two bounds are inclusive, meaning all the numbers including 0 and 5 will be reached.
Tip: In this example, we see the Exit For statement. This statement breaks out of the enclosing For-loop.
Exit works in all loops and Subs.
Please see the detailed information about Exit.
Program that uses For: VB.NET Module Module1 Sub Main() ' This loop goes from 0 to 5. For value As Integer = 0 To 5 ' Exit condition if the value is three. If (value = 3) Then Exit For End If Console.WriteLine(value) Next End Sub End Module Output 0 1 2
In this example, we want to decrement the counter variable instead of increment it. In other words, we go down not up. We start at 10 and then continue down in steps of 2 to 0. We print the value in each iteration.
Also: The Step keyword is used near the end of the For-statement and it is the delta each loop iteration will have.
If you want to decrement by 1 each time, you can use -1.
If you want to increment by 1, use 1.
Program that uses For Step: VB.NET Module Module1 Sub Main() ' This loop uses Step to go down 2 each iteration. For value As Integer = 10 To 0 Step -2 Console.WriteLine(value) Next End Sub End Module Output 10 8 6 4 2 0
The For and For Each loops can be used on String variables. This gives us a way to check or process each character in the Object data. String loops are an alternative to using Regex for modifying and creating Strings.Loop Over String Regex.Replace
The For-loop is one of the core looping constructs in the VB.NET language. It provides a way to explicitly specify the loop bounds. Because of this, it often leads to more robust code.
And: With the for-keyword, fewer careless bugs caused by incorrect loop boundaries may occur in programs.