Using FOR EACH Loop in VB helps to repeat a group of statements for each statement in a collection.
FOR EACH loop usually using when you have execute every single item of a sentence. ie, element in an array, element in a file or element in a string.
|
1 2 3 |
For each [item] in group ‘statement to execute Next [item] |
- Item – Item in the group
- Group –Group containing items
- statement to execute – Statement which you want to execute.
Mainly used loops in VB.NET:
FOR NEXT Loop
FOR EACH Loop
WHILE Loop
DO WHILE Loop
FOR EACH Loop
Using FOR EACH Loop in VB – Complete Code
|
1 2 3 4 5 6 7 8 9 |
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim StrName = "Welcome to VB World" For Each singleChar In StrName MsgBox(singleChar) Next End Sub End Class |
Using FOR EACH Loop in VB – Working
- Step 1: Assign “Welcome to VB World” to the string variable.
- Step 2: SingleChar will extract each character from the given string.
- Step 3: Executing body, where you get the result through the messagebox.
Nested Loops - FOR EACH Loop in VB
- Nested Loops helps to nest FOR EACH by putting other loop inside another.
Nested Loops – Complete Code
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Create list of numers 'Create list of characters Dim number() As Integer = {1, 4, 5} Dim letters() As String = {"a", "b", "c"} For Each numbers As Integer In number For Each letter As String In letters MsgBox(numbers.ToString() & letter & " ") Next Next End Sub End Class |
- When you nest loops, each loop must have a unique element variable.
Exit For and Continue For - FOR EACH Loop in VB
- The Exit For statement is used to exit the execution of the code inside the For Each Statement.
- The Continue For statement transfers control immediately to the next iteration of the loop
Exit For and Continue For – Complete Code
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim NumerSq() As Integer = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} For Each number As Integer In NumerSq ' If number is between 5 and 7, continue ' with the next iteration. If number >= 5 And number <= 7 Then Continue For End If 'Display the number MsgBox(number.ToString & "") 'if number is 10 exit the loop If number = 10 Then Exit For End If Next End Sub End Class |
Using FOR EACH Loop in VB






