Do Loops

     Do Loops are an important part of programing and definitely something you should expiriment with a little.  The first command is Do, which starts the loop.  The second, of course, is Loop.   When it comes to Loop it goes back to Do and performs everything again.  If you do not tell the program to exit the loop it will go on forever!   You can exit a loop with the command Exit Do.  This exits the loop from wherever the command is in the loop and starts carrying out the code immediately after the Loop statement.  Here is an example:

Dim Counter As Integer
Do
Counter = Counter + 1
If Counter = 10 Then Exit Do
Loop

     Now if you put this into your program this is what it would do.  It would first come to Do and start the loop.  Each time it comes to Counter it adds 1 to the it, and after it adds one to Counter it quickly checks to see if Counter = 10(See If...Then...Else Tutorial).  If it does = 10 then Exit Do exits the loop.  If Counter does not equal 10 then it performs the loop again.

    You are probably wondreing what would happen if you forgot to make a way for the loop to finish and exit.  Well, like I said before, it would just go on forever.  Now, don't panac, there is a way to end your program in Visual Basic.   Push Ctrl and Break at the same time.  This will put you back in Visual Basic where you can correct your problem.  I encourage you to now read the For Next Loops tutorial, because it will teach you an even better way to loop in a situation like this.  Do not take me wrong, Do Loops are important and used frequently, but in some cases it is better to use a For Next loop.  So please go read the For Next Loops tutorial.

    Did you understand that?  You can download the sample program here, which will show you the loop in action.

Back

Copyright ©2000 by Kyle Baker.  Please read our disclaimer.