| Posted at 06:41 AM on December 24, 2008 |
Let us recap, quickly.
Your writing VBA code, you know where to find the VBA editor, how to create a subroutine, what a variable is and how to get a message box on screen. Not bad for 5 minutes work, it sure took me a lot longer than that to learn it! What were you worried about? VBA is easy.
Now we?re going to learn how to make instructions repeat themselves, we call this a loop. If you have OCD, then this is the Lesson for you. There are a lot of ways to do loops in VBA, the simplest is to say "Do these instructions, repeat this many times". In code we'd write whats called a For ... Next loop, like this
For intLoop = 1 to 10
?.Some instruction or other
Next intLoop
So, if we put a loop in our PutAppleInBox subroutine, we get this
Sub PutAppleInBox()
Dim intRepeatThisLoop
Dim intBoxOfApples As Integer
For intRepeatThisLoop = 1 To 10
intBoxOfApples = intBoxOfApples + 1
Next
MsgBox ("There are " & intBoxOfApples & " apples in the box")
End Sub
Go try it now, modify your previous program, remember to press F5 key to run the code. I changed "There is" to "There are", just to make the sentence look right. Now you've gone loopy too.
You can change the 1 to 10 to any number you like; you can even go backward like this
For intRepeatThisLoop = 10 to 1 step -1
By now, you're probably thinking either
Categories: VBA Tutorials (mixed nuts)