VBA  IV- Looping

 

Looping is a very useful feature of Visual Basic because it makes repetitive works easier. In lesson9 of my tutorial, I have shown that there two kinds of loops in VB, the Do...Loop and the For.......Next  loop. Today I am going to demonstrate the For....Next loop using MS Excel editor with two examples.

Example 1:

Private Sub CommandButton1_Click()
Dim i As Integer
For i = 1 To 10
Cells(i, 1).Value = i
Next
End Sub

In this program, you place the command button 1 on the spreadsheet then click on it to go into the Visual Basic editor. When you click on the button will fill cells(1,1) with the value of 1, cells(2,1) with the value of 2, cells(3,1) with the value of 3......until cells (10,1) with the value of 10. The position of each cell in the Excel spreadsheet is referenced with cells(i,j), where i represents row and j represent column.

In example 2, I used the nested loop to put the values of i+j from cells(1,1),cells(1,2),cells(1,3),cells(1,4),cells(1,5) ..........until cells(10,5). The codes and output are shown below. So you see, you can learn the basics of VB just using MS Excel . More examples will be shown in the coming VB today, check back often!

 

Example 1

Example 2

Codes of Example 2

Private Sub CommandButton1_Click()
Dim i, j As Integer
For i = 1 To 10
For j = 1 To 5
Cells(i, j).Value = i + j
Next j
Next i
End Sub
 

 

 

 

 

 

 [Previous Lesson] [Back to VBA Tutorial] [Next Lesson]