Vba nested loops in Excel
Nested loop is nothing but a loop within a loop. It is a double loop. You can make a triple loop and q quadruple loop.
There may be any number of loops within a loop, but the loops has to be properly nested without any conflict.
This feature of Excel is very useful in comparing a range of cells and is most often used in Excel Programming.
The following example illustrates the nested loop.
The code compares each value of a cell in column A with that of column B.
- Sub Nested_Loop()
- Dim i, j As Integer
- For i = 1 To 2
- For j = 1 To 2
- If Sheets(1).Range("A" & CStr(i)) = Sheets(1).Range("B" & CStr(j)) Then
- MsgBox "A" & CStr(i) & " and B" & CStr(j) & " are Same"
- Else
- MsgBox "A" & CStr(i) & " and B" & CStr(j) & " are different"
- End If
- Next j
- Next i
- End Sub
The above code compares A1 to A2 with that of B1 to B2 and the result is as shown below
A1 and B1 are different
A1 and B2 are different
A2 and B1 are different
A2 and B2 are different
Note the placement of "Next" statement in the example. The latest loop should be closed first