The Microsoft Excel FOR...NEXT statement is used to create a FOR loop so that you can execute VBA code a fixed number of times.
The FOR...NEXT statement is a built-in function in Excel that is categorized as a Logical Function. It can be used as a VBA function (VBA) in Excel.
Single Loop:
Below is the
example of single For …Loop :
Sub Singleloopexample()
Dim i As Integer
For i = 1 To 5
ThisWorkbook.Worksheets("Output").Cells(i + 1, 1).Value = "LoopIncrement." & i
Next i
End Sub
Dim i As Integer
For i = 1 To 5
ThisWorkbook.Worksheets("Output").Cells(i + 1, 1).Value = "LoopIncrement." & i
Next i
End Sub
Single Loop
changing increment:
By using “STEP”
parameter the counter value can be Incremented & Decremented .
#Positive Increment:
Sub Singleloopexample_step()
Dim i As Integer
For i = 1 To 5 Step 2
ThisWorkbook.Worksheets("Output").Cells(i + 1, 1).Value = "LoopIncrement." & i
Next i
End Sub
Output:Dim i As Integer
For i = 1 To 5 Step 2
ThisWorkbook.Worksheets("Output").Cells(i + 1, 1).Value = "LoopIncrement." & i
Next i
End Sub
#Negative Increment
Sub NegativeIncrement()
Dim i As Integer
j = 2
For i = 7 To 1 Step -2
ThisWorkbook.Worksheets("Output").Cells(j, 1).Value = "LoopIncrement." & i
j = j + 1
Next i
End Sub
Output:Dim i As Integer
j = 2
For i = 7 To 1 Step -2
ThisWorkbook.Worksheets("Output").Cells(j, 1).Value = "LoopIncrement." & i
j = j + 1
Next i
End Sub
Nested For loop:
Below is the few
example of nested for loop.
Double For…….
Loop :
In below example
two for loop being used. Outer for loop being controlled by “i” and inner loop controlled
by “j” .
Below is the
Sub Doubleloop()
Dim i As Integer, j As Integer
For i = 1 To 6
For j = 1 To 2
ThisWorkbook.Worksheets("Output").Cells(i + 1, j).Value = "LoopIncrement." & i & "*" & j
Next j
Next i
End Sub
Dim i As Integer, j As Integer
For i = 1 To 6
For j = 1 To 2
ThisWorkbook.Worksheets("Output").Cells(i + 1, j).Value = "LoopIncrement." & i & "*" & j
Next j
Next i
End Sub
Output:
As Double For ... Loop , we can use Triple For Loop also.
You May like to Read this also
No comments:
Post a Comment