Reputation: 121
If current cell value = 4 then "i" value of FOR loop must STEP 4 ie For i=0 to lastrow-6 STEP 4. And If current cell value = 3 then "i" value of FOR loop must STEP 3 ie For i=0 to lastrow-6 STEP 3.I tried following code but no matter what value I give to "X" inside the FOR loop it always takes 4 ie For i=0 to lastrow-6 STEP X=4
Sub pap()
With ActiveSheet
lastrow = .Cells(.Rows.Count, 9).End(xlUp).Row
x = 4
For i = 0 To lastrow - 6 Step x
If ActiveSheet.Cells(7 + i, 9) = 4 Then
ActiveSheet.Cells(7 + i, 7) = 4
x = 4
End If
If ActiveSheet.Cells(7 + i, 9) = 3 Then
ActiveSheet.Cells(7 + i, 7) = 3
x = 3
End If
Next i
End With
End Sub
Upvotes: 0
Views: 665
Reputation: 36
You can re-think about this and manually move the variable i. You need to be careful because when you write next i, i is moved of steps x according to your code. So the code below does what you wanted to do, and moves manually i according to your variable step width. Then I subtract one because of the next instruction that you need to put. I hope it does help!
So look at this code:
Sub pap()
With ActiveSheet
lastrow = .Cells(.Rows.Count, 9).End(xlUp).Row
x = 4
For i = 0 To lastrow - 6
If ActiveSheet.Cells(7 + i, 9) = 4 Then
x = 4
End If
If ActiveSheet.Cells(7 + i, 9) = 3 Then
x = 3
End If
ActiveSheet.Cells(7 + i, 7) = 4
i = i + x - 1
Next i
End With
End Sub
Upvotes: 1
Reputation: 17533
Although I understand your idea, I would advise you not to do this: for-loops are generally known as stepping using a fix value. If you want to step using a variable value, you might better use a while-loop:
i = 0
while i<= LastRow - 6
do
if <condition> then i = i + 3
else i = i + 4
end if
wend
I'm advising you to consider, not only the question whether or not your code is working, but also: imagine that somebody needs to modify your code (or even you yourself after a large period of time), such strange ways of working make it difficult to work on.
Upvotes: 1