ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   For To / Next loop doesn't update... (https://www.excelbanter.com/excel-programming/411214-next-loop-doesnt-update.html)

TFriis

For To / Next loop doesn't update...
 
How come this sub only runs through i=1 and i=2, when k is obviously
updated during loop?

Sub Test()

k = 2
For i = 1 To k
Debug.Print k
If k = 2 Then k = 4
Next i

End Sub

I know this sub solves the problem, but I find Do While loops to be
clumsy - any other solutions?

Sub test2()

k = 2
i = 1
Do While i <= k
Debug.Print k
If k = 2 Then k = 4
i = i + 1
Loop


End Sub

TFriis

For To / Next loop doesn't update...
 
Better examples - but same result :)

Sub Test()

k = 4
For i = 1 To k
Debug.Print "k = " & k & " i = " & i
If i = 2 Then k = 8
Next i

End Sub

Sub test2()

k = 2
i = 1
Do While i <= k
Debug.Print "k = " & k & " i = " & i
If k = 2 Then k = 4
i = i + 1
Loop


End Sub

Bob Phillips

For To / Next loop doesn't update...
 
Because the loop limit is set when it executes the For statement, it does
not get updated just because the variable that initially set it gets
changed.

--
---
HTH

Bob


(there's no email, no snail mail, but somewhere should be gmail in my addy)



"TFriis" wrote in message
...
How come this sub only runs through i=1 and i=2, when k is obviously
updated during loop?

Sub Test()

k = 2
For i = 1 To k
Debug.Print k
If k = 2 Then k = 4
Next i

End Sub

I know this sub solves the problem, but I find Do While loops to be
clumsy - any other solutions?

Sub test2()

k = 2
i = 1
Do While i <= k
Debug.Print k
If k = 2 Then k = 4
i = i + 1
Loop


End Sub





All times are GMT +1. The time now is 12:27 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com