PDA

View Full Version : VB Looping Statements



eugenelyn
09-09-2008, 06:26 PM
Greetings! I'm eugenelyn and this is my first post in the VBA Express forum.

I'm slightly confused with the kinds of looping statements VB has:

Do... Until vs Do... Loop... Until
Do... While vs Do... Loop While
For... To... Next
For... Each
For... To... Step... Next


I kinda find it hard to differentiate Do... Until and Do... Loop... Until loops, as well as Do... While and Do... Loop... While Loops.

Any help/elaborations would really be appreciated. Thank you very much and more power to VBA express!

CreganTur
09-10-2008, 05:59 AM
Welcome to the forums! Always good to see new members.

At first glance all of the different loop statements do seem very similar, but each one does something different. For all of the code snippets I've provided- you can put them into a Sub in any module, place your cursor somewhere inside the Sub, and then press F5 to make it run- you will see results print to the Immediate Window. This is true for everything but the For...Each loop- you'll need to put it in a Sub in the module behind a form that has some objects on it.


Do... Until vs Do... Loop... Until
This structure will continue to loop until a set condition is met. The difference between Do Until...Loop and Do...Loop Until is simple- if the condition is met the very first time the loop is run, then the Do Until...Loop will not run a loop, but the Do...Loop Until will run once.
Dim i As Integer
i = 0
Do Until i = 10
Debug.Print i
i = i + 1
Loop


Do... While vs Do... Loop While
This structure will run through iterations as long as a set condition is true. Also, the differences between the 2 structures is the same as above- Do...Loop While will run once even if the condition is met the first time the loop runs.
Dim i As Integer
i = 0
Do While i < 10
Debug.Print i
i = i + 1
Loop


For... To... Next | For... To... Step... Next
These are the same thing- the only difference is the Step parameter is used.
These loops run a set number of times- this number of iterations is determined by the numbers you set in the For...To part of the statement. Step tells the loop how to increase the count- if you don't use this parameter, then it will increase by 1 by default. If you want to count up by 3, then you use the Step parameter. The following example will run from 1 to 100, but increasing by 2:
Dim x As Long
For x = 1 To 100 Step 2
Debug.Print x
Next


For... Each
This loop structure is used to loop through each object in a collection. Put this code behind a form that has some objects on it- it will make them all invisible.
Dim ctrl As Control
For Each ctrl In Me.Controls
ctrl.Visible = False
Next

eugenelyn
09-19-2008, 08:56 AM
My apologies for the delayed response. n_n;;

Thank you very much for the clear explanation, Sir Randy!