VBA FOR NEXT loop in Excel
The 'For Next' loop statement offers a way to execute a script for a given number of times thus reducing the code size.
The 'For Next' is a Control flow statement and is widely known as "For loop".
This statement comes to rescue when data from a large number of Cells has to be read or manipulated in Excel.
Example: The following example iterates 10 times and stores the value in an Array.
- Sub for_loop()
- Dim i As Integer
- Dim j(10) As Integer
- For i = 1 To 10
- j(i) = i
- MsgBox j(i)
- Next i
- End Sub
- For var_name=1 To 10 Step 1
- Next var_name
The For loop always ends with "Next" Keyword followed by variable_name.
The "Step" keyword defines how much to increase on each iteration, The default is 1.
A negative "Step" indicates iteration in Decreasing order.
A Messagebox is displayed 10 times from 1 to 10