Multiple Loops in Excel Vba

In this article, we are going to learn how to use multiple loops in VBA. Two commonly used loops in VBA are the For loop and the For Each loop. We are going to use the For Next Loop first.

Adding command button

To add a command button click on “Insert” and then select “Command Button” from ActiveX group.

Multiple Loops insert command button

Create a command button.

Multiple Loops create command button

Write click on the command button and Select “View Code”.

Multiple Loops select view code

Nesting Vba Loops

Write this line of code. After writing the code, close the window by clicking on the red X button on the top left of the screen.

Private Sub CommandButton1_Click()
Dim i As Integer, j As Integer
For i=1 To 6
For j=1 To 2
Cells (i, j).Value=100
Next j
Next i
End Sub

Multiple Loops vba code

Click on the command button to see this result.

Multiple Loops click command button

In this code, the outer loop (controlled by the variable i) iterates from 1 to 6. For each iteration of the outer loop, the inner loop (controlled by the variable j) iterates from 1 to 2.

This means the code within the inner loop (Cells(i, j).Value = 100) is executed twice for each iteration of the outer loop.

The Cells(i, j) property refers to a specific cell in the worksheet, where i represents the row number and j represents the column number. Therefore, this code sets the value of cells A1, B1, A2, B2, A3, B3, A4, B4, A5, B5, A6, and B6 to 100.

This is how to implement two for loops using Excel VBA.