PDA

View Full Version : Help with For Loop Structure



Saladsamurai
11-19-2009, 03:25 PM
I want my routine to do some stuff for all i = 3, 5, 10, 15 20

I tried this, but for some reason i is taking on a value of 0. Any thoughts?

Sub Test2()

Dim i As Integer
Dim j As Integer
Range("A1:A50").Delete

j = 1
For i = 3 And i = 5 To 20 Step 5
Cells(j, 1) = i
j = j + 1
Next i



End Sub


Edit: changed i values for clarity. Also i is taking on 0 because it is testing to see if i = 3 AND 5, which will never happen. Therefore it returns 0.

I have a simple workaround, but I am still curious to see how something like this could be done.

RolfJ
11-19-2009, 04:40 PM
You could use an array for the i variables like in this example:

Sub Test2_WithArray()
Dim iArray() As Variant
iArray = Array(3, 5, 10, 15, 20)
Dim i As Variant
Dim j As Integer
j = 1
For Each i In iArray
Cells(j, 1) = i
j = j + 1
Next i
End Sub

Saladsamurai
11-20-2009, 07:02 AM
You could use an array for the i variables like in this example:

Sub Test2_WithArray()
Dim iArray() As Variant
iArray = Array(3, 5, 10, 15, 20)
Dim i As Variant
Dim j As Integer
j = 1
For Each i In iArray
Cells(j, 1) = i
j = j + 1
Next i
End Sub


Thanks for the suggestion. However, I would like to keep from having to input all of t he 'i' values to an array.

It is only the initial value of 'i' that differs. So I can use the: "For i = 5 to X Step 5" format....but I need it to first run an iteration for the case i = 3.

I guess I could just add another index or something.

Bob Phillips
11-20-2009, 07:42 AM
Sub Test2()

Dim i As Long
Dim j As Long
Range("A1:A50").Delete

j = 1
For i = 1 To 20 Step 5
If i = 1 Then i = 5
Cells(j, 1) = i
j = j + 1
Next i

End Sub