Thursday, 17 February 2011

Driving me loopy

There are three types of loops used in Visual Basic:

For...Next
Do While
Loop...Until

Each performs basically the same function - running a piece of code multiple times - yet they are each somewhat specialised.

The For...Next loop is used to run a piece of code a set number of times (it is the only loop with a set number of iterations). As its name suggest, it is used when a function needs to be carried out FOR each of several items, for example when doing formatting for each name in a list. The For...Next loop changes a variable every time it runs, so that the function can be specialised for each item.

The Do While loop runs a piece of code if a condition is true. If the loop starts running, here must be a section inside the loop to either alter the condition or break out of the loop, otherwise it will run indefinitely. If the condition is initially false, the Do While loop does not run at all. It could be used instead of a Loop...Until loop nested in an If statement.

The Loop...Until loop is exactly the same as the Do While loop except that it will always run the code inside before checking whether the condition is true; that is, the code inside will always run at least once even if the condition is false.

Loops can be nested inside each other or used in conjunction with control flow statements.

1 comment: