Vba For Loop
Vba For Loop
Here's
the basic syntax:
Basic Syntax:
vba
Copy
For counter = start To end [Step step]
' Code to be executed
Next counter
counter: The variable that will change during each loop iteration.
Step step: (optional) How much the counter will increase or decrease each time. If
you don't provide a step, it will default to 1.
vba
Copy
Sub ForLoopExample()
Dim i As Integer
For i = 1 To 5
Debug.Print i ' Prints numbers 1 to 5
Next i
End Sub
Example 2: Using the Step Keyword
If you want the loop to increment or decrement by something other than 1, use the
Step keyword. This example will print numbers from 1 to 10, increasing by 2 each
time:
vba
Copy
Sub ForLoopWithStep()
Dim i As Integer
For i = 1 To 10 Step 2
Debug.Print i ' Prints 1, 3, 5, 7, 9
Next i
End Sub
Example 3: Looping Backwards
You can also use the For loop to count backwards. Here's an example that loops from
10 down to 1:
vba
Copy
Sub ForLoopBackward()
Dim i As Integer
For i = 10 To 1 Step -1
Debug.Print i ' Prints 10, 9, 8, ..., 1
Next i
End Sub
Key Points:
Next counter is used to go to the next iteration.
The Step is optional but useful when you want to control the increment/decrement.
You can use a For loop to go forward or backward, depending on the start, end, and
Step values.