Adding Control Statements

When working with Do While and Do Until loops, you may have situations where you want to jump out of a loop before executing the remaining statements in the loop. You can do this by using the Exit Do statement. You can place an Exit Do statement anywhere within the body of the loop, which can contain multiple Exit Do statements. When VBA encounters an Exit Do statement, the control immediately transfers out of the current loop to the next statement outside the loop.

Typically a conditional statement such as If Then appears before the Exit Do statement. The conditional statement looks for a condition to meet and then executes the Exit Do statement. The following code uses an If Then statement to check a second condition, as indicated. This code continues to execute as long as Condition1 is true. Each time the loop executes, the If Then statement checks to see if the value of Condition2 has changed. When the value of Condition2 is true, the loop exits immediately, and processing continues with the next statement outside the loop.

Example:

Do While Condition1 = True If Condition2 = True

Exit Do End If

Loop

Specify the body of the loop.

^0 Type Loop to end the Do Until loop.

Specify the body of the loop.

—H Increment the variable.

m

IT1"!™!«, 'insert"To!"

Tools Data

Window

elp

Type

a question for help t

0 X

m £ I ™ - »o

*è\ a

m <#*100

* 1- ® .

.10 , 1 B

M. A . .

B2

f* 5.75

A

B

c

D

E

F

G

H

1

J

1

Total

Total with Tax

1

V

$5.00

$5.75

3

$6.50

Ï7.48

4

$17.65

$20.30

5

$335.00

$442.75

6

$52.00

Ï59.8G

7

$683.00

$785.45

8

$14.50

$16.68

9

$3.00

$3.45

10

$11.45

$13.17

11

12

13

14

1fi

16

17

18

19

1

2U

V1

22

23

24

25

—■

N

» H|\ Sheet 1

Sheet2 / Sheet4 / Sheet3 /

1

► ir

Rea

V

^0 Type Loop to end the Do Until loop.

■ If you skipped step 5, type Until followed by the condition of the loop.

• Switch to Excel and run the macro.

■ The macro repeats until the specified condition is true.

0 0

Post a comment