Paul The Programmer

60 Second Blog

Lesson 6. The Art of Repeating yourself

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

  1. This guys a genius and teaches VBA really easily
  2. This guys a nutcase and should be committed
  3. Lets do another lesson (that's what I was thinking)

 

Categories: VBA Tutorials (mixed nuts)

Post a Comment

Already a member? Sign In

0 Comments

Dont Miss a thing.

Get FREE updates from me by email. Get a mini profile that lives on my website. Learn and teach. Communicate and share ideas with other members. Join here.

Recent Blog Entries

by paultheprogrammer | 0 comments
by paultheprogrammer | 1 comments
by paultheprogrammer | 0 comments
by paultheprogrammer | 2 comments

Recent Forum Posts

by paultheprogrammer 10 months ago

Recent Videos