In this part of the video series you’ll learn the following:
Overview Responding to user actions at runtime
building a table.
A few words about code loops
If you want code in a loop to run at least once, your should evaluate the loop at the end of the loop.
In this bit of code the result is going to be 20.
Sub Looper() Dim intCounter As Integer intCounter = 5 Do While intCounter < 20 intCounter = intCounter + 1 Loop MsgBox intCounter End Sub
Because intCounter is going to be incremented at every step of the loop. When intCounter equals 19, which is less than 20, so it gets incremented again.
At the last loop try, the value of intCounter equals 20, so the the condition is now true and intCounter leaves the loop, and goes to the MsgBox function.
Try to guess what the result of intIncrement will be?
Sub Looper2() Dim intCounter As Integer Dim intIncrement As Integer intIncrement = 1 For intCounter = 1 To 4 intIncrement = intIncrement + 1 Next intCounter MsgBox intIncrement End Sub
If you said “5”, you would be correct.
You see intIncrement gets instantiated at 1. The For Loop goes from 1 to 4. “1, 2, 3, 4”. So, when the loop goes to 1, the intIncrement gets incremented to 2, then 3, 4, 5.
That’s 4 iterations.
So it goes exactly 4 times and intIncrement increases to 5, leaving the For…Next looping structure would be best for running a loop exactly four times.