Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
DiscussionsAccessExcelInfoPathOutlookPowerPointPublisherWord
DirectoryUser Groups
Related Topics
Outlook ExpressInternet ExplorerWindowsMS Server ProductsMore Topics ...

MS Office Forum / Excel / Programming / May 2008

Tip: Looking for answers? Try searching our database.

For To / Next loop doesn't update...

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
TFriis - 20 May 2008 10:51 GMT
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 - 20 May 2008 10:55 GMT
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 - 20 May 2008 11:50 GMT
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.

Signature

---
HTH

Bob

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

> How come this sub only runs through i=1 and i=2, when k is obviously
> updated during loop?
[quoted text clipped - 23 lines]
>
> End Sub
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.