Professional Documents
Culture Documents
FOR Loop
Ex 01
Sub Loop1()
Dim StartNumber As Integer
Dim EndNumber As Integer
EndNumber = 5
End Sub
Ex 02
Sub Loop2()
'Fills cells A1:A56 with values of X by looping' --- Comment
'Increase value of X by 1 in each loop' --- Comment
Dim X As Integer
For X = 1 To 56
Range("A" & X).Value = X
Next X
End Sub
Sub Loop3()
' Fills cells B1:B56 with the 56 background colours' --- Comment
Dim X As Integer
For X = 1 To 56
Range("B" & X).Select
With Selection.Interior
.ColorIndex = X
.Pattern = xlSolid
End With
Next X
End Sub
Example 4
Sub Loop4()
' Fills every second cell from C1:C50 with values of X' --- Comment
Dim X As Integer
For X = 1 To 50 Step 2
Range("C" & X).Value = X
Next X
End Sub
Example 5
Sub Loop5()
' Fills cells from D1:D50 with values of X' --- Comment
' In this case X decreases by 1' --- Comment
Dim X As Integer, Row As Integer
Row = 1
For X = 50 To 0 Step -1
Range("D" & Row).Value = X
Row = Row + 1
Next X
End Sub
Sub Loop6()
' Fills every second cell from E1:E100 with values of X' --- Comment
' In this case X decreases by 2' --- Comment
Dim X As Integer, Row As Integer
Row = 1
For X = 100 To 0 Step -2
Range("E" & Row).Value = X
Row = Row + 2
Next X
End Sub
Example 7
The For … Next loop has the following syntax:
Next counter
Do Loop
Dim i As Integer
i = 1
Do Until i > 6
Cells(i, 1).Value = 20
i = i + 1
Loop
Do While loop
Dim n as Integer
N=0
Do while n < 11
n = n + 1
Loop