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.

  1. Sub Nested_Loop()
  2. Dim i, j As Integer
  3. For i = 1 To 2
  4. For j = 1 To 2
  5. If Sheets(1).Range("A" & CStr(i)) = Sheets(1).Range("B" & CStr(j)) Then
  6. MsgBox "A" & CStr(i) & " and B" & CStr(j) & " are Same"
  7. Else
  8. MsgBox "A" & CStr(i) & " and B" & CStr(j) & " are different"
  9. End If
  10. Next j
  11. Next i
  12. End Sub

excel vba nested loops

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

excel vba nested loops

A1 and B2 are different

excel vba nested loops

A2 and B1 are different

excel vba nested loops

A2 and B2 are different

excel vba nested loops

Note the placement of "Next" statement in the example. The latest loop should be closed first

 

You can find similar Excel Questions and Answer hereunder

1) How can I find number of months that has elapsed given 2 dates?

2) How to use flash fill in Excel. How to fill cells very quickly and automatically.

3) What is a methods. Methods are action that can be performed by an object

4) Applying a countif formula only to visible cells in a filtered list in Excel

5) How can I loop through all ActiveX checkboxes in WorkSheet and set them to Unchecked status?

6) How can I have text autocomplete based on values previously entered in Column?

7) How can I hide a specific Shape in my WorkSheet?

8) Vba list all files in a folder in Excel

9) How do I find the median salary of employees with the same skillset in my Organization?

10) How can I loop through all WorkSheets and get their names using VBA?

 

Here the previous and next chapter