Using DoLoop to create a loop

The Do...Loop block is one method of setting up a loop in code to execute statements repeatedly. The loop requires two lines of code: one at the top and one at the bottom. You have a lot of flexibility when defining a Do...Loop. In fact, there are two forms of syntax for creating these loops. The first is the following:

Do [{While | Until} condition] [statements] [Exit Do] [statements] Loop

The second form of syntax provides the option of defining the condition at the bottom of the loop, like this:

[statements] [Exit Do] [statements] Loop [{While | Until} condition]

In both instances, statements refers to any number of VBA statements, and condition is an expression that can result in either True or False. The vertical bar (also called a pipe) indicates that you can use one word or the other. For example, you can use the word While or the word Until, but you can't use both. Other types of loops use similar constructs. So rather than dwell on this type of loop right now, look at some other ways to set up loops.

For now, just realize that when you look at existing code, any statements between the Do and Loop statements are executed repeatedly. Statements outside the loop are still executed once each, from top to bottom. Only the statements inside the loop are executed repeatedly, as illustrated in Figure 4-5.

Code execution

Figure 4-5:

Statements inside a Do...Loop loop are executed repeatedly.

'Any VBA statement or comment 'Any VBA statement or comment Any VBA statement or comment

'Any VBA statement or comment 'Any VBA statement or comment Any VBA statement or comment

Loop

'Any VBA statement or comment 'Any VBA statement or comment Any VBA statement or comment

Was this article helpful?

0 0

Responses

  • TANTA
    How to create the doloop statement?
    8 years ago

Post a comment