Tải bản đầy đủ - 0 (trang)
Table 2-2. Assignment in Various Languages

Table 2-2. Assignment in Various Languages

Tải bản đầy đủ - 0trang

Let me emphasize that commenting code is almost as much of an art as writing the code itself. I

have often seen comments similar to the following:

' Set x equal to 5

x = 5



This comment is pretty useless, since the actual code is self-explanatory. It simply wastes time and

space. (In a teaching tool, such as this book, you may find some comments that would otherwise

be left out of a professionally written program.)

A good test of the quality of your comments is to read just the comments (not the code) to see if

you get a good sense not only of what the program is designed to do, but also of the steps that are

used to accomplish the program's goal. For example, here are the comments from a short BASIC

program that appears in Appendix F:

' BASIC program to compute the average

' of a set of at most 100 numbers

' Ask for the number of numbers

' If Num is between 1 and 100 then proceed

' Loop to collect the numbers to average

' Ask for next number

' Add the number to the running sum

' Compute the average

' Display the average



2.2.2 Readability

Readability is also a subjective matter. What is readable to one person may not be readable to

another. In fact, it is probably fair to say that what is readable to the author of a program is likely

to be less readable to everyone else, at least to some degree. It is wise to keep this in mind when

you start programming (that is, assuming you want others to be able to read your programs).

One of the greatest offenders to code readability is the infamous GOTO statement, of which many

languages (including VBA) have some variety or other. It is not my intention to dwell upon the

GOTO statement, but it will help illustrate the issue of good programming style.

The GOTO statement is very simple—it just redirects program execution to another location. For

instance, the following BASIC code asks the user for a positive number. If the user enters a

nonpositive number, the GOTO portion of the code redirects execution to the first line of the

program (the label TryAgain). This causes the entire program to be executed again. In short, the

program will repeat until the user enters a positive number:

TryAgain:

INPUT "Enter a positive number: ", x

IF x <= 0 THEN GOTO TryAgain



While the previous example may not be good programming style, it is at least readable. However,

the following code is much more difficult to read:

TryAgain:

INPUT "Enter a number between 1 and 100: ", x

IF x > 100 THEN GOTO TooLarge

IF x <= 0 THEN GOTO TooSmall

PRINT "Your number is: ", x



9



GOTO Done

TooLarge:

PRINT "Your number is too large"

GOTO TryAgain

TooSmall:

PRINT "Your number is too small"

GOTO TryAgain

Done:

END



Because we need to jump around in the program in order to follow the possible flows of execution,

this type of programming is sometimes referred to as spaghetti code. Imagine this style of

programming in a program that was thousands of lines long! The following version is much more

readable, although it is still not the best possible style:

TryAgain:

INPUT "Enter a number between 1 and 100: ", x

IF x > 100 THEN

PRINT "Your number is too large"

GOTO TryAgain

ELSEIF x <= 0 THEN

PRINT "Your number is too small"

GOTO TryAgain

END IF

PRINT "Your number is: ", x

END



The following code does the same job, but avoids the use of the GOTO statement altogether, and

would no doubt be considered better programming style by most programmers:

DO

INPUT "Enter a number between 1 and 100: ", x

IF x > 100 THEN

PRINT "Your number is too large"

ELSEIF x <= 0 THEN

PRINT "Your number is too small"

END IF

LOOP UNTIL x >= 1 AND x <= 100

PRINT "Your number is: ", x

END



Readability can also suffer at the hands of programmers who like to think that their code is

especially clever or elegant but, in reality, just turns out to be hard to read and error-prone. This is

especially easy to do when programming in the C language. For instance, as a very simple

example, consider the following three lines in C:

x = x + 1;

x = x + i;

i = i - 1;



The first line adds 1 to x , the second line adds i to x , and the third line subtracts 1 from i. This

code is certainly readable (if not terribly meaningful). However, it can also be written as:

x = ++x+i--;



This may be some programmer's idea of clever programming, but to me it is just obnoxious. This

is why a sagacious programmer always favors readability over cleverness or elegance.



10



2.2.3 Modularity

Another major issue that relates to readability is that of modular programming. In the early days

of PC programming (in BASIC), most programs were written as a single code unit, sometimes

with many hundreds or even thousands of lines of code. It is not easy to follow such a program,

especially six months after it was written. Also, these programs tended to contain the same code

segments over and over, which is a waste of time and space.

The following BASIC example will illustrate the point. Line numbers have been added for

reference. (Don't worry too much about following each line of code. You can still follow the

discussion in any case.)

10



' Program to reverse the letters in your name



20

30

40

50

60

70

80



' Do first name

INPUT "Enter your first name: ", name$

reverse$ = ""

FOR i = LEN(name$) TO 1 STEP -1

reverse$ = reverse$ + MID$(name$, i, 1)

NEXT i

PRINT "First name reversed: " + reverse$



90

100

110

120

130

140

150



' Do middle name

INPUT "Enter your middle name: ", name$

reverse$ = ""

FOR i = LEN(name$) TO 1 STEP -1

reverse$ = reverse$ + MID$(name$, i, 1)

NEXT i

PRINT "Middle name reversed: " + reverse$



160

170

180

190

200

210

220



' Do last name

INPUT "Enter your last name: ", name$

reverse$ = ""

FOR i = LEN(name$) TO 1 STEP -1

reverse$ = reverse$ + MID$(name$, i, 1)

NEXT i

PRINT "Last name reversed: " + reverse$



Now, observe that lines 40-70, 110-140, and 180-210 (in bold) are identical. This is a waste of

space. A better approach would be to separate the code that does the reversing of a string name

into a separate code module and call upon that module thrice, as in the following example:

' Program to reverse your name

DECLARE FUNCTION Reverse$ (name$)

' Do first name

INPUT "Enter your first name: ", name$

PRINT "First name reversed: " + Reverse$(name$)

' Do middle name

INPUT "Enter your middle name: ", name$

PRINT "Middle name reversed: " + Reverse$(name$)

' Do last name

INPUT "Enter your last name: ", name$

PRINT "Last name reversed: " + Reverse$(name$)



The separate code module to reverse a string is:



11



' Reverses a string

FUNCTION Reverse$ (aname$)

Temp$ = ""

FOR i = LEN(aname$) TO 1 STEP -1

Temp$ = Temp$ + MID$(aname$, i, 1)

NEXT i

Reverse$ = Temp$

END FUNCTION



Of course, the saving in space is not great in this example, but you can imagine what would

happen if we replace the reversing procedure by one that requires several hundred lines of code

and if we want to perform this procedure a few hundred times in the main program. This

modularization could save thousands of lines of code.

There is another very important advantage to modular programming. If we decide to write another

program that requires reversing some strings, we can simply add our string-reversing code module

to the new program, without having to write any new code. Indeed, professional programmers

often compile custom code libraries containing useful code modules that can be slipped into new

applications when necessary.

It is hard to overestimate the importance of modular programming. Fortunately, as we will see,

VBA makes it easy to create modular programs.

Generally speaking, there are two main groups of code modules: functions and subroutines. The

difference between them is that functions return a value whereas subroutines do not. (Of course,

we may choose not to use the value returned from a function.) For instance, the Reverse function

described in the previous example returns the reversed string. On the other hand, the following

code module performs a service but does not return a value—it simply pauses a certain number of

seconds (given by sec):

SUB delay (sec)

' Get the current time

StartTime = TIMER

' Enter a do-nothing loop for sec seconds

DO

LOOP UNTIL TIMER - StartTime > sec

END SUB



Functions and subroutines are extremely common in modern coding. Together, they are referred to

as procedures.



12



Chapter 3. The Visual Basic Editor, Part I

The first step in becoming an Excel VBA programmer is to become familiar with the environment

in which Excel VBA programming is done. Each of the main Office applications has a

programming environment referred to as its Integrated Development Environment (IDE).

Microsoft also refers to this programming environment as the Visual Basic Editor.

Our plan in this chapter and Chapter 4 is to describe the major components of the Excel IDE. We

realize that you are probably anxious to get to some actual programming, but it is necessary to

gain some familiarity with the IDE before you can use it. Nevertheless, you may want to read

quickly through this chapter and the next and then refer back to them as needed.

In Office 97, the Word, Excel, and PowerPoint IDEs have the same appearance, shown in Figure

3-1. (Beginning with Office 2000, Microsoft Access also uses this IDE.) To start the Excel IDE,

simply choose Visual Basic Editor from the Macros submenu of the Tools menu, or hit Alt-F11.

Figure 3-1. The Excel VBA IDE



Let us take a look at some of the components of this IDE.



3.1 The Project Window

The window in the upper-left corner of the client area (below the toolbar) is called the Project

Explorer. Figure 3-2 shows a close-up of this window.

Figure 3-2. The Project Explorer



13



Note that the Project Explorer has a treelike structure, similar to the Windows Explorer's folders

pane (the left-hand pane). Each entry in the Project Explorer is called a node. The top nodes, of

which there are two in Figure 3-2, represent the currently open Excel VBA projects (hence the

name Project Explorer). The view of each project can be expanded or contracted by clicking on

the small boxes (just as with Windows Explorer). Note that there is one project for each currently

open Excel workbook.



3.1.1 Project Names

Each project has a name, which the programmer can choose. The default name for a project is

VBAProject. The top node for each project is labeled:

ProjectName (WorkbookName)



where ProjectName is the name of the project and WorkbookName is the name of the Excel

workbook.



3.1.2 Project Contents

At the level immediately below the top (project) level, as Figure 3-2 shows, there are nodes named:

Microsoft Excel Objects

Forms

Modules

Classes

Under the Microsoft Excel Objects node, there is a node for each worksheet and chartsheet in the

workbook, as well as a special node called ThisWorkbook, which represents the workbook itself.

These nodes provide access to the code windows for each of these objects, where we can write our

code.



14



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Table 2-2. Assignment in Various Languages

Tải bản đầy đủ ngay(0 tr)

×