Showing posts with label VBA for Excel For Loop. Show all posts
Showing posts with label VBA for Excel For Loop. Show all posts

Friday, January 11, 2008

Basic VBA structures: For...Next Loops

For...Next Loops:

To cycle through a loop use a "for loop" structure, use the For...Next syntax. This works as in the following example:

To cycle through a loop using the variable i as a counter, the structure looks like:

'First declare the variable
Dim i As Integer

'Now create the loop.
'This is one that will run 10 times.
'Each time you can use the current value of i in a formula

For i = 1 To 10
Worksheets("Sheet1").Cells(i,1).Value = i*2
Next i


The code above inputs the values into the first column of Sheet1 as such:

2
4
6
8
10
12
14
16
18
20