Loops


Now we are well into the aspects of visual basic programming we shall look at loops. These are especially useful with arrays as you can easily loop thourgh the entire contents of the array to edit or display each element.

For Loops


I use for loops very heavily when I program as they are very easy and quick to use. A large number of people (including myself) are lazy about declaring the variable used and just leave it undeclared. It is standard to use 'i' as the variables name (or j, k etc. if they are stacked). The basic syntax is:
For i = 0 to 6
	YourCode
Next
This will run the code 7 times with i being increased by 1 each time. The numbers always run in sequence. You are able to change the step for loops so that each time there is an increase of more or less than 1.
For i = 0 to 6 Step 2
Or
For i = 6 to 0 Step -1
Visual Basic will give you a nice friendly message when you run the program if you forget the 'Next'.

While Loops


While loops continually loop through while their statement is true. WARNING - These will loop forever and crash Visual Basic if the statement never becomes false. You lose all your work since the last save.
Here is the syntax:
While Condition is true
	Code
Wend
If you intend the user to be able to be able to do thing while it is still looping then you should include 'DoEvents' somewhere in the code. This tells the Operating system to do anything else that needs doing like pick up mouse movement etc.

Do...While


Thies is the same as the previous but the expression is evaluated after the code has run. This means that the code will always run at least once.
Do
	Code
While Condition is true

Do...Loop


This carries the severe warning from the while loop and is even more dangerous because there is not built in conditional statement. It can be exited by using the 'Exit Do' command in your code. I use it in my 3D programs to continuously render the scene until the program is ended. Always use 'DoEvents inside Do...Loop statements.

You will find that if you close the form with the close button then the program will continue to run in the background and must be stopped with the visual basic stop button. To stop this happening we must end the program when the form unloads. First we must get to the forms unload event. To do this we can double click the form and then look at the top just above the code window but below he main toolbars. There should be two dropdown boxes, one with form written in it and the other with click written in it. Pick the one with click written in it and find 'Unload'. Now you should have a form unload sub. Inside the two lines of code of this sub you should type 'End'. This will make sure the program ends.
Do
DoEvents

Loop


© Jonathan Waller 2005; QuantumState Visual Basic