Paul The Programmer

North East Software and Websites

60 Second Blog

Lesson 7. Loops with strings attached

Posted at 05:04 AM on December 29, 2008

Previously, we saw that you can drive yourself loopy, and repeat instructions over and over again, a time saver once you get it right. But what if you want to stop the loop early because something has happened?

 

These are called conditional loops. Easy real world definition:

 

Going with your girl, stopping because you have an argument, getting back together again, another argumental split and so on.

 

Expanding a bit on the PutAppleInBox subroutine, we can add an IF….THEN…..ENDIF clause (not Santa). We do this to get the routine to “jump” over a few numbers, once a certain number or condition has been reached (my age went from 15 to 18 every Friday night so I could go to the pub):

 

Sub PutAppleInBox()

Dim intRepeatThisLoop As Integer

Dim intBoxOfApples As Integer

For intRepeatThisLoop = 1 To 10

   If intBoxOfApples = 8 Then

      intBoxOfApples = 10

   End If

   intBoxOfApples = intBoxOfApples + 1

Next

MsgBox ("There are " & intBoxOfApples & " apples in the box")

End Sub

 

Using the code (above), once intBoxOfApples reaches 8, the code makes intBoxOfApples = 10 and completely misses out 9. This ends the For loop early.

 

There are many uses of If:

  • If only she went out with me
  • If only I hadn’t gone out with him
  • If only The tooth fairy hadn’t pulled out all my teeth the night I slept with my head under the pillow.

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 over a year ago

Recent Videos