Adding Control Statements

Although VBA does not require you to indent your code, you can use indentation to improve readability. Indenting enables you to more easily look at the layout of the code without reading each line. When dealing with conditional statements, such as If Then statements and looping statements, most programmers typically indent the code within these statements for readability. The following example shows how you can indent the code body of a For Next loop to let people easily locate the loop's beginning and end. The example also indents the If Then statement body code to show its location.

Example:

For I = 1 To

If J <

10 Then

J =

J + 1

End If

Next

If you have an If Then statement that consists of only one body statement, you can combine the If Then statement with the body statement and eliminate the End If statement.

TYPE THIS:

If Sum <10 Then Sum

= Sum + 1

'This is equivalent

to typing the following:

If Sum < 10 Then

Sum = Sum + 1

End If

The code adds 1 to the sum as long as the sum is less than 10.

□ Switch to Excel and run the associated macro.

□ Switch to Excel and run the associated macro.

m

File Edit View Insert

Format Tools Data

Window Help

■ Type a question fc

S X

H,- ^

& £

-il l\

M #100

% -

j Ari

» 10 -

B I U

a Ü $ % , tôS ¿8 tF iF _ -

to' à. • -r

A1

f* 23

A

B

c

D

E

F

G

H

1

J

K

1

23

34.5

2

14

3

56

4

70

5

23

6

12

7

69

8

245

9

13

10

511

11

12

13

14

15

16

17

18

19

20

21

22

23

24

—1

25

> n|\ Sheet 1 i Sheet2 /

heet4 / Sheet3 /

1 *

HI

Ready

-■ The If Then statement checks the condition and executes the appropriate statements based upon the results.

0 0

Post a comment