This book is more than the usual computer disk and text combination. The book that you now hold contains a working
copy of Microsoft Visual Basic For Windows, a complete Windows programming development system. Along with Visual Basic, you get a
fantastic (if I may say so myself) introduction to programming within the Visual Basic environment. In addition to Visual
Basic and the text, you also get every program listed in this book, so you can spend less time typing and more time learning.
If you have programmed in other languages, hold on to your hatsVisual Basic is unlike other programming languages.
The primary difference is that Visual Basic is fun to work with. The word fun simply does not apply to many other
programming languages. With Visual Basic, you create most of your programs by clicking and moving your mouse. Instead of
programming, you really build programs. Visual Basic is one of the few programming tools with which you can efficiently design
your program while you create your program.
This unit describes what programming is all about. You will learn a
little about the history of programming, especially the movement of BASIC through computer history. (Visual Basic finds its roots in the more traditional BASIC language.) Get ready to
learn how Visual Basic streamlines your programming life.
Note: This unit spends a lot of time describing the background and importance of programming and early programming languages. This background serves two purposes. First, by learning about the history of programming, you will have a better idea where today's programming tools are headed. Second, you will appreciate more fully the incredible power, ease, and versatility that Visual Basic offers over other programming languages. Visual Basic's capabilities were beyond anyone's imagination just a few years ago.
Concept: If you want your computer to do exactly what you want it to do, you must write a program.
A computer does nothing on its own. In fact, a computer is
a dumb machine with no intelligence whatsoever. Despite what you might read in science fiction stories, a computer does nothing more than blindly follow instructions supplied by a programmer.
Computers cannot think.
Definition: A program is a set of instructions that tells the computer exactly what to do.
When someone buys a computer today, the computer sits on the
desk doing nothing until he loads a program into the computer's internal memory and starts running the program. Just as a VCR does not record shows on its own without being programmed to do
so, a computer requires detailed instructions found only in
programs.
Suppose that you own rental properties and want to use your computer to track your tenant records. Your computer will not help you out in any way until you load and run a rental property program. Where do you find such a program? There
are two ways to
obtain programs for computers. You can
Buy one and hope that the program does exactly what you want it to do.
Write your own program.
It's much easier and faster
to buy a program that you need. Thousands of programs are on the market today. In fact, there are so many programs out there that you might not see the need for writing your own programs.
If you can find a program that does exactly what you want,
you are ahead of the game. If you find a program that meets your exact requirements, you should buy that program because purchasing a program is often less expensive and much quicker than
writing the same program yourself or hiring programmers to write it
for you.
Think about this for a moment, though: If there are so many programs sold today that do virtually everything, why are programming languages such as Visual Basic continuing to break previous sales records each year? The answer is simple:
People buy a
computer so that the computer will do jobs that they need done. Firms cannot adapt their business to a computer program. They must find programs, or write their own programs, so that the computer processes information according to the
business procedures
already in place. The only way to ensure that a program exactly fits the needs of a firm is for the firm to develop its own programs.
Business people are not the only ones who need custom-designed programs. No two people
manage their finances exactly the same way; no two scientists need computers for exactly the same kinds of computations; and no two graphic artists need the same
kinds of computer drawing tools. Although people buy spreadsheets and word processors for
their general-purpose computing needs, many people require specialized programs for specific jobs.
The art of programming computers is rewarding not only from a requirements standpoint, but also on a more personal level. Programming computers is
fun! Just as a sculptor looks on a finished work of clay, programmers are often proud of the programs that
they write. By the time you finish this book, you will have written programs that were not available before you wrote them. When you want your
computer to do something specific and you cannot find a program that does the job exactly the way you want, you
will be able to design and write the program yourself.
Some Programs are Changeable: There is a third method for getting exactly the program that you need if you want to computerize your company's accounting records. Accounting software firms often sell not only accounting programs but also the source code for those programs. The source code is a listing of the program's instructions. By having access to the source code, you can take what the software company wrote and modify the behavior of the program to suit your own requirements.
By starting with a functional program instead of starting from scratch, you save programming time and money. Sadly, most non-accounting software firms do not supply the source code. Most programs sold today have been compiled. After compiling, the source code is translated into a locked-in executable program. The bottom line is that you cannot easily change the behavior of compiled programs. For most programs, therefore, you have the choice of buying them or writing them yourself from scratch.
Definition: Code is another name for program.
There are many ways to write programs for computers.
In the next section, you'll learn how the process of entering programs progressed from switches on the front of the computer to clicking and pointing with the mouse today. The majority of programs now
in use are supplied in the form of code listings,
which often comprise pages of line after line of computer instructions. Visual Basic helps take the drudgery out of codingthat is, writingprograms. Visual Basic enables you to move elements and
place graphical images on the screen with the
mouse instead of requiring that you give written and detailed screen instructions as required by languages that came before Visual Basic.
Tip: For a complete description of the programming process, a comprehensive overview of programming languages, and a guided tour through the business of programming, check out Absolute Beginner's Guide to Programming (Sams Publishing, 1993).
Review: No single program pleases everyone. When a company sells a program, it must be general enough to please most purchasers. Some people need programs to behave in a specific
manner in order to fulfill a
specific need. They must resort to writing their own programs. Luckily, Visual Basic takes a lot of the pain out of writing programs.
Concept: Computers cannot understand just any language. You must learn a language that your computer knows before you
can write programs for your computer.
Definition: An application is yet another name for program.
Many people
use computers all day long for word processing, database storage, and spreadsheet analysis, without realizing what is going on behind the scenes. You must always keep in mind that computers cannot think. Your computer does not know how to be
a word
processor. If you want your computer to do word processing, you must supply detailed instructions in the form of a program. Only by following the detailed instructions of a word processor program that you load can your computer perform word
processing.
It would be nice if writing a program is as easy as telling the computer what you want done. Many people can handle ambiguous instructions, but computers are not smart enough to understand vague requirements. Computers can only follow orders given
to
them, and you must supply those orders in the form of a program. Therefore, you must supply the programs that you write. Writing programs, especially complex programs, takes time and several procedural steps. Visual Basic speeds the process of creating
programs, but even with Visual Basic some programs take time to write and perfect.
Definition: A bug is a program error.
Figure 1.1 shows you the typical steps that most programmers go through when writing programs. First, you have an idea for a program. Next, you use a program-development system, such as Visual Basic, to write the program.
Errors, or bugs, often
appear in programs because of the details needed for even the simplest of programs. Therefore, you must test the program thoroughly and fix the errors. Fixing errors is called debugging. Once all the errors are out of
the program, you have a
finished application.
Figure 1.1. Writing a program involves several steps.
The second step, writing the source code, is the most tedious part of programming. Remember
that the source code is the actual programming instructions that the computer is to follow. You will spend most of your programming time working on the source
code so that you end up with a program whose instructions direct the computer in the way that
you want.
There are many ways to write the source code for programs. Although today's computers are more powerful than earlier machines in terms of memory capacity and speed, today's computers are no smarter than the very first computer. In the
late 1940s,
programmers had to write programs for those early computers just as today's programmers must do. The difference lies in the way today's programmers write programs. Today's programming toolsVisual Basic is a shining exampleare far
more powerful.
They enable you to develop programs more powerful than before and with less effort on your part.
The very early computers were not programmed through keyboards and mice. As a matter of fact, the first few computers did not even have keyboards! The first computers had to be programmed by routing wires from
component to component. Instead of
programmers, electrical engineers programmed the early computers.
Those hard-wired programming methods were simply too tedious to be productive. If a different calculation was needed, somebody would have to
rewire the computer. Programmers had to have electrical and engineering experience just to make a computer do
something. There had to be a way to speed up the process.
Those early computers had memory similar to the way in which today's
computers have memory. The difference is that the early memory was minusculeeven the largest computers had only a few hundred memory locations for data storage. Despite the short
supply of memory, one of the computer experts of the time developed
the idea of using the memory to hold both data and the code that instructed the computer on a task. Until that point, the "code" consisted of the hard-wired circuitry.
Tip: By putting the computer's instructions inside the memory along with data, the computer programs were easier to change because the memory could be changed. Engineers were no longer required to rewire the computer every time the program needed changing.
The computer scientists put a panel of switches on those early computers. Figure 1.2 shows a simple representation of those switches. The programmers would flip the switches into a
series of unique On and Off states, press the Enter button, and repeat
the process until a series of instructions that looked like the following "program" appeared in the program memory:
On Off On On Off Off Off On Off On On Off On On Off Off Off Off Off On On Off On Off On On On On Off Off Off On Off Off On Off Off On On Off On On Off On On Off Off On Off Off On Off On On On Off
Figure 1.2. The switch panel
eliminated the hand wiring.
Definition: The original On-and-Off programming was called machine language.
Although this On-and-Off program is virtually indecipherable, each combination of On and Off switches represents a single instruction. By combining several instructions that operated on data located elsewhere in the machine's
memory, a complicated
thirty-instruction program might not do anything more than multiply two numbers! Despite the difficulties involved, such a lightning-fast calculation would have been unheard of before computers. The military immediately began using
computers for
trajectories and other calculations.
Tip: By seeing the short history of programming, you will really appreciate what Visual Basic can do when you start using Visual Basic for your programs.
The world of computers began moving forward with the switch panel. More memory was added, and the programs got more powerful. Sometime in the late 1940s,
somebody got the bright idea of replacing the switch panel with a typewriter-like keyboard. Instead
of assigning On and Off combinations to mean Add and Store, programmers could actually type the words Add and Store on the keyboard. The
computer would analyze the instruction, look up the On and Off combinations needed, and set the memory
switches internally.
Machine Language is Dead!Long Live Machine Language!: Luckily, you do not have to write programs in the On-and-Off machine language anymore. The computer languages today are much closer to spoken speech than On and Off switches can ever hope to be. Even so, today's most powerful computer, programmed with advanced programming tools such as Visual Basic, still recognizes only machine language.
People do not like machine language because it is too difficult to use. Computers do not like anything else. The job of all programming languages is to take the source code that you type in a programming language and to convert it to machine language so that the computer can execute those instructions.
Once programmers got hold of keyboards, there was no stopping them. The languages grew from the primitive On-and-Off system to
higher-level languages that read more like spoken text. Listing 1.1 shows an example of a short FORTRAN program from the early
days of these high-level languages. Although this FORTRAN program will be cryptic to you, the more textual approach to
programming, as opposed to On and Off switches, opened doors for more people to become programmers. The software industry blossomed in
the 1950s, and programs went from simple calculating tools to complete business and scientific applications.
Note: FORTRAN stands for FORmula TRANslator. It is used primarily in mathematical and scientific programming. Although FORTRAN was one of the earliest high-level programming languages, many computer installations still use FORTRAN programs today. Much of the Visual Basic language was founded in principles of the early FORTRAN language.
Listing 1.1. An early FORTRAN program.
WRITE (6, 10) 10 FORMAT('** Payroll Calculations **') WRITE (6, 11) 11 FORMAT('** Enter the employee's ID, hours, and pay rate') TAXRAT = 0.25 101 READ(5, 102, END=900) IDEMP, HRSWRK, RATE 102 FORMAT(I5, 1X, I3, F5.2) IF (HRSWRK .GT. 40) GOTO 300 *******COMPUTE REGULAR PAY GRSPAY = HRSWRK * RATE GOTO 500 300 OVRHRS = HRSWRK - 40 *******COMPUTE OVERTIME PAY OTGRS = OVRHRS * RATE * 1.5 GRSPAY = 40.0 * RATE + OTGRS 500 TAXES = GRSPAY * TAXRAT PAYNET = GRSPAY - TAXES WRITE (6,503) IDEMP, PAYNET 503 FORMAT('EMP: ', I3, 2X, 'NET PAY:', F6.2) GOTO 101 *******END-OF-JOB PROCESSING 900 END
If you are
unfamiliar with FORTRAN programs or with programming in any other language, you probably will not understand much of what you see in Listing 1.1. You might, however, be able to tell from some of the words, that the code performs payroll
calculations of
some kind. It is true that FORTRAN does not produce extremely readable code, but the commands such as IF, GOTO, and WRITE, improved programmer productivity greatly over what programmers had to do before such languages came along.
With high-level
languages such as FORTRAN, the 1950s and 1960s saw an incredible distribution of new software. Programming became more accessible to more people because of the easier-to-use programming languages. The increased number of programs brought
a tremendous
increase in the number of computers sold. Companies, laboratories, and universities purchased computers. There was no turning back the computer era once so many people had access to so much computing power. As computer companies sold more
computers,
competition produced less expensive and more powerful machines. And you thought that the 1990s were exciting!
Definition: Syntax refers to the spelling and grammar of languages.
Even though programming languages were easier to learn, there was still much need for easier programming methods. Some Dartmouth College professors decided to write an easier
programming language based on FORTRAN but with fewer details than FORTRAN
required. Those professors developed BASIC, the language that enabled students to write programs because of its easier format and less restrictive syntax than FORTRANs.
Note: BASIC is an acronym for Beginner's All-purpose Symbolic Instruction Code. The acronym's meaning is almost as long asand much more difficult to remember thanthe BASIC language itself.
Listing 1.2 shows the BASIC equivalent of the FORTRAN program that you saw in Listing 1.1. To programming newcomers, this BASIC
listing might not be significantly easier to understand than the FORTRAN code. Nevertheless, the BASIC language is a little
cleaner and slightly less cryptic than its FORTRAN predecessor. Although programming still took effort, BASIC took some of the
rough edges off programming, and it brought more people to the programming craft.
Listing 1.2. A BASIC program.
10 PRINT "** Payroll Calculations **" 20 PRINT "** Enter the employee's ID, hours, and pay rate" 30 TAXRAT = .25 40 INPUT IDEMP$, HRSWRK, RATE 50 IF (IDEMP$ = "END") THEN GOTO 160 60 IF (HRSWRK > 40) GOTO 70 70 REM *******COMPUTE REGULAR PAY 80 GRSPAY = HRSWRK * RATE 90 GOTO 110 100 OVRHRS = HRSWRK - 40 110 REM *******COMPUTE OVERTIME PAY 120 OTGRS = OVRHRS * RATE * 1.5 130 GRSPAY = 40 * RATE + OTGRS 140 TAXES = GRSPAY * TAXRAT 150 PAYNET = GRSPAY - TAXES 160 PRINT "EMP: "; IDEMP$; "NET PAY:"; PAYNET 170 GOTO 20 180 END
Well into the 1980s, the rate at which the number of programmers grew remained high. Despite all new programmers, the programming tools themselves really did not advance much. Many people developed new
programming languages. Despite their "new and
improved" claims, most of the languages retained the textual procedural quality that FORTRAN and BASIC offered.
Large-scale programming tool improvements did not occur until a hardware
breakthrough occurred: NASA's space efforts developed the microchip, and microcomputers were born. Now, instead of new and potential programmers, desktop computers opened the door
for millions of would-be programmers. These programmers demanded easier
programming tools.
Definition: QBasic is a recent BASIC language clone.
Efforts were made to improve the friendliness
of programming languages like BASIC. New versions of BASIC, such as QBasic, enabled programmers to write more powerful programs with less effort. Programmers could also write programs that had a less rigid
style than those before. Listing 1.3 shows a
QBasic version of the payroll calculation shown in the previous two listings. As you can see, the language is getting less strict and more free-form.
Listing 1.3. A QBasic program.
TaxRate = .25 PRINT "** Payroll Calculations **" PRINT "** Enter the employee's ID, hours, and pay rate" INPUT IdOfEmp$, HrsWorked, Rate DO UNTIL (IdOfEmp$ = "END") IF (HrsWorked <= 40) THEN ' *******Compute regular pay GrossPay = HrsWorked * Rate ELSE ' *******Compute overtime pay OverTimeHours = HrsWorked - 40 OverTimeGross = OverTimeHours * Rate * 1.5 GrossPay = 40 * Rate + OverTimeGross END IF Taxes = GrossPay * TaxRate PayNet = GrossPay - Taxes PRINT "Emp: "; IdOfEmp$; "Net Pay:"; PayNet INPUT IdOfEmp$, HrsWorked, Rate LOOP END
Definition: Computers generate output on screens and printers.
Just as a recipe has a result, the cooked meal, instructions in a program produce an important result. The result of the programming effort is the finished program that makes the computer perform a directed task, such as payroll processing. After
entering a program or loading a program from the disk, you must tell the computer to run, or execute, the program. The computer then follows the program's instructions and produces the output.
If you entered the code in Listing 1.3 into the
QBasic programming language, the following output might result:
** Payroll Calculations ** ** Enter the employee's ID, hours, and pay rate ? KL823, 40, 9.25 Emp: KL823 Net Pay: 277.5 ? PO341, 35, 10 Emp: PO341 Net Pay: 262.5 ? LP543, 40, 10 Emp: LP543 Net Pay: 300 ? END, 0, 0
Note: The previous QBasic code requires that the user tell the program that there are no more employees to process by typing END as an employee ID and zero amounts for the hours and pay rate.
Tip: This output would be different if the user entered different data, because the program would calculate different payroll results.
Definition: Input is the data that the user enters.
As you can see from the execution of this program, the program takes the user's input and calculates net pay amounts. Input can come from sources
other than the user. Programs might get input from a disk file, a modem connected to the telephone, or from
other programs running along with yours. Users do not always see the output, either. Programs often perform calculations and data manipulation and
send the output of that processing to disk files or to other computers over modem lines.
Figure 1.3 illustrates the program flow from writing the program to generating output, such as the payroll output you see here.
Figure 1.3. The program's instructions produce the output.
Warning: The output you get after typing with a word processor would be the text on paper or on the screen. The output from other programs might be as diverse as payroll reports, calculations, or graphics. The program's instructions determines what the program produces.
Syntax is the grammar of a language.
Bugs are as frustrating in computer programs as they are in computer programmer's houses. Rarely will a program that you write work the first time you run it. There are two kinds of errors: Syntax
errorssounds like "sin tax" and
is worse in many waysand logic errors. Since you do not know the Visual Basic programming language yet, this simple phrase demonstrates the two kinds of errors that can appear in your code:
There are two errrors in this sentence.
What are the two errors? I'll wait...
The first error, a syntax error, is easy to spot. errrors is misspelled. The logic error takes more time to find. The logic error is that the entire
sentence is logically wrongthere is only one error, the syntax error errrors.
When you begin to write programs, this example sentence may come back to haunt you a bit. Syntax errors are easy to catch because Visual Basic catches all
of them for you. In other words, if you type Tezt when Visual Basic expects you to type Text,
Visual Basic immediately displays an error message box in the center of your screen. Visual Basic is extremely stubborn when it comes to syntax errors because it
refuses to execute your program until you remove all the syntax errors in the code.
When you make a logic error, however, Visual Basic cannot help you out. For example, if you were writing a payroll calculation routine and accidentally subtracted
$50 from everybody's paycheck, Visual Basic has no way of knowing that you should not
subtract that amount. If you tell Visual Basic to subtract the amountusing correct syntax, of courseVisual Basic subtracts the amount. Only until your
employees beat your door down will you know that a logic error took place.
Tip: Thoroughly test your programs before you distribute them or use them for important work. Run the program using all combinations of input to find and correct as many logic errors as possible.
Definition: GUI stands for Graphical User Interface.
A challenging programming problem arose when advanced GUI visual environments, such as Microsoft Windows, appeared in the 1980s. GUI environments require more advanced and difficult programming efforts than text-based
computing environments. Although
users and programmers wanted easier tools, GUI environments demanded more complex programming tools.
Definition: An event can be a Windows mouse click, a key press, a menu selection, or an internal Windows activity.
It is relatively easy to produce the text-based output shown earlier. It is much more difficult to produce
Windows-like screens such as the one shown in Figure 1.4. The user does not have to enter the ID, hours worked, and amounts in any preset order.
Neither does the user have to press the three command buttons at the right of the screen in any order. In
Windows programs, a specific event determines the next course of action. A Windows program is called an event-driven program as opposed to a
text-based procedural program. In Windows, the user determines what happens next by triggering an event to
which the Visual Basic program responds.
Figure 1.4. Users randomly control event-driven programs.
Review: Computer programming has progressed a long
way from the wiring panels of the early days. Once keyboards were added, what programmers could do grew by leaps and bounds. Actually, it was not until the
development of Visual Basic that another great leap in programming tools arrived. The power of
programs that you can create with Visual Basic, given the simplicity of Visual Basic's environment, produces as much computer programming advantage today as the
keyboard provided over the switch panel. As Yogi Berra once said, "It ain't bragging if
it's true!"
Concept: As Windows programming tools
are developed, their complexity seems to increase. The Microsoft Windows environment requires much more complicated programming efforts than DOS-based non-Windows programs
require. Visual Basic bucks the trend by providing a simple approach to writing
Windows programs while retaining all the beginning and advanced programming language instructions found in QBasic.
Definition: Text-based programs are often called procedural programs.
Procedural languages such as FORTRAN and QBasic simply don't work well for a GUI environment. The problemactually, the primary advantage for usersof GUIs is the
event-driven processing explained in the previous section. The user does not
always do the same thing in the same order. That is, a user might want to select from a pull-down menu, click a mouse button, type text, or compute a mathematical answer, and he
might do those tasks in virtually any order. Text-based procedural programming
languages essentially required that the program dictate the order of the user's actions. Windows requires a different approach. The traditional programming languages cannot
handle the GUI approach well at all.
It is possible to write event-driven programs in procedural languages. The majority of Windows programs in use today were written in the C language, a procedural language more similar in style to FORTRAN than
to Visual Basic, although C and FORTRAN
differ greatly in their approach and syntax. Nevertheless, C programmers face great challenges when using C for Windows programs because languages such as C are procedural whereas Windows is event-driven.
Several powerful programming solutions have been devised that aid Windows programmers. A relatively new programming concept called object-oriented programming (or OOP for short) better lends itself to Windows-like event-driven programming
than languages such as FORTRAN, BASIC, or C. Even OOP, however, puts a strain on its programmers that today's busy and backlogged programming departments do not have the resources to handle.
The big problem is that as computers get easier for
users by supplying graphical environments such as Windows, the programs that the users use become harder to develop. Therefore, as the demand for these GUI programs increase, so does the backlog of
programs that need to be written.
Microsoft
introduced a new programming language, Visual Basic, a few years ago. The advantages of Visual Basic became immediately apparent. They are
The great thing about Visual Basic is that the program looks almost exactly like the output screen that results. In other words, to design and write the
simple program that produced Figure 1.3, you would place text, buttons, and lines onto the screen,
using the visual tools supplied with Visual Basic, until your "program" looked like what you wanted your finished Windows program to look like.
Such placement of visual elements would takes pages and pages of typed instructions using a
traditional procedural programming language.
Note: After the success of Visual Basic for Windows, Microsoft developed Visual Basic for DOS. Visual Basic for DOS found extremely limited success, however, and is now extinct.
Before you can learn to program with Visual Basic, you
must get a feel for the tool itself. The second half of this lesson, Unit 2, introduces you to Visual Basic itself. You will learn how to install the Visual Basic disk that
comes with this book, start Visual Basic, and manipulate
the screens of Visual Basic. Once you master the mechanics of Visual Basic, the second lesson dives right into programming by walking you through your first full-functional Visual Basic application
from design to execution.
Visual Basic is Event-Driven and Procedural: Don't think that the days of program listings are gone forever. As a matter of fact, one of the most important components of Visual Basic is its procedural BASIC-like programming language underneath the visual environment. When you begin to extend your Visual Basic programming by developing more powerful programs, you will need to combine the visual elements of the language with the QBasic-like routines.
Warning: This unit ends here without describing the details of Visual Basic because Visual Basic's details are the rest of this book's job. Now that you have a fundamental grasp of programming and the Windows programming challenges, you are ready to begin taking a rewarding tutorial of Visual Basic for the remainder of this book. In twelve easy lessons, you will be a Visual Basic master!
Review: In many ways, writing programs the old-fashioned waythat is, writing page after page of text instructions that the computer
will eventually followis somewhat like a long and arduous recipe.
The cook starts at the first instruction in the recipe and must be careful not to skip steps. Such listings are vital, and although the recipe might throw in a picture or two, the
cook must follow the recipe sequentially if the finished meal is to taste
good.
Writing programs with Visual Basic is much more akin to using a VCR than following a step-by-step recipe. In all fairness, though, even the most complicated of VCRs
are easier to program than complex Visual Basic applications. Visual Basic, though, is
still one of the easiest and fastest tools you can find to develop Windows applications.
Note: Most of the parts in this book end with a Review as well as a Stop & Type section, which enables you reinforce the section's topics with a hands-on programming exercise. The primary purpose of this first unit has been to teach you the basics of programming from a historical perspective. Therefore, there are no hands-on topics for this unit.
Note: Because this unit was descriptive, it contains no What's the Output?, Find the Bug, or Write Code That... sections.