30.04.2017 Views

4523756273

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

158<br />

Part III: Programming Concepts<br />

Sub DoUntilDemo()<br />

Do Until IsEmpty(ActiveCell.Value)<br />

ActiveCell.Value = ActiveCell.Value * 2<br />

ActiveCell.Offset(1, 0).Select<br />

Loop<br />

End Sub<br />

Just like with the Do-While loop, you may encounter a different form of the<br />

Do-Until loop — a Do-Loop Until loop. The following example, which has the<br />

same effect as the preceding procedure, demonstrates an alternate syntax for<br />

this type of loop:<br />

Sub DoLoopUntilDemo()<br />

Do<br />

ActiveCell.Value = ActiveCell.Value * 2<br />

ActiveCell.Offset(1, 0).Select<br />

Loop Until IsEmpty(ActiveCell.Value)<br />

End Sub<br />

There is a subtle difference in how the Do-Until loop and the Do-Loop Until<br />

loop operate. In the former, the test is performed at the beginning of the loop,<br />

before anything in the body of the loop is executed. This means that it is possible<br />

that the code in the loop body will not be executed if the test condition<br />

is met. In the latter version, the condition is tested at the end of the loop.<br />

Therefore, at a minimum, the Do-Loop Until loop always results in the body of<br />

the loop being executed once.<br />

Another way to think about it is like this: The Do-While loop keeps looping as<br />

long as the condition is True. The Do-Until loop keeps looping as long as the<br />

condition is False.<br />

Looping through a Collection<br />

VBA supports yet another type of looping — looping through each object in a<br />

collection of objects. Recall that a collection consists of a number of objects<br />

of the same type. For example, Excel has a collection of all open workbooks<br />

(the Workbooks collection), and each workbook has a collection of worksheets<br />

(the Worksheets collection).<br />

When you need to loop through each object in a collection, use the For Each-<br />

Next structure. The syntax is<br />

For Each element In collection<br />

[statements]<br />

[Exit For]<br />

[statements]<br />

Next [element]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!