0% found this document useful (0 votes)
4 views2 pages

Vba For Loop

The document explains the For loop in programming, detailing its syntax and components such as counter, start, end, and optional Step. It provides three examples: a basic loop printing numbers 1 to 5, a loop using Step to print odd numbers from 1 to 10, and a backward loop counting down from 10 to 1. Key points emphasize the use of Next counter and the flexibility of the Step keyword for controlling increments or decrements.

Uploaded by

abhishek sapra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Vba For Loop

The document explains the For loop in programming, detailing its syntax and components such as counter, start, end, and optional Step. It provides three examples: a basic loop printing numbers 1 to 5, a loop using Step to print odd numbers from 1 to 10, and a backward loop counting down from 10 to 1. Key points emphasize the use of Next counter and the flexibility of the Step keyword for controlling increments or decrements.

Uploaded by

abhishek sapra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

A For loop allows you to repeat a block of code a specific number of times.

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.

start: The starting value for the counter.

end: The ending value for the counter.

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.

Example 1: Basic For Loop


This example will print the numbers 1 to 5 in the Immediate Window:

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.

You might also like