Hour 6


During this hour you will learn

Understanding the VB Program Structure

This lesson introduces you to Visual Basic programs. Now that you've worked with Visual Basic's Form window and learned the fundamentals of placing controls and setting control properties, it's time to add punch to your programs. Learning a programming language--especially the Visual Basic programming language--is much easier than learning a foreign language! To make the language easier, this lesson describes the structure of Visual Basic programs and shows how to document your programs to make them easier to maintain later.

Topic 1: Project Structure

Until this lesson, you've only scratched the surface of Visual Basic application development, as you might guess. Nevertheless, you've already come a long way, and you can already create simple Windows programs. When you add Visual Basic code, you can turn simple programs into powerful programs that process data and perform the work you need done.

Before you learn the Visual Basic language details, take a few minutes this hour to see the "big picture." This topic section introduces you to the structure of Visual Basic programs. Every VB application's Project window describes the application's structure.


Have you programmed before? If you've programmed strictly in a text-based language, such as COBOL, FORTRAN, or QBasic, you should study this hour's lesson. If you've programmed in a windowed high-level language such as Visual C++, you can probably scan this lesson to make sure that you understand the concepts unique to Visual Basic. No matter what your programming background is, this lesson is critical because you need to understand Visual Basic's structure fully before learning the language.

Overview

Before Windows came along, an application primarily consisted of one long text-based program without any graphical additions such as a form with controls. Through the years as computers and software advanced, programmers began breaking their code into small sections, called modules, subroutines, or procedures (Visual Basic uses all three terms today), so applications began changing formats from one long program to several small routines that worked together as a single program.

When Windows came along, the visual interface had to be part of the picture. Somehow, programmers had to combine text-based instructions with a graphical interface. Sadly, programmers had to work with several different tools--some for the text program parts and some for the visual parts. For a time, a Windows program was an awkward collection of files that programmers had to glue together into a working Windows application.

Visual Basic not only supplies the glue, but keeps things organized for you. Visual Basic gives you a platform on which you work with a Windows application that's a collection of organized forms, event procedures, and other code that work together in a common development environment.

Code Everywhere

You've already seen code in event procedures such as the following:

Private Sub cmdGetHappy_Click()

  imgViewHappy.Picture = LoadPicture("C:\My Documents\VB

                         [ccc]NightSchool\Happy.bmp")

End Sub

The event procedure code is a small portion of any Visual Basic application. The more forms your application has, the more controls your application will likely have. The more controls your application has, the more event procedures your application will likely have to make those controls respond to events.

Event procedures aren't the only place where you'll find Visual Basic code. In most applications, VB code also appears inside one or more Visual Basic modules. The module code is data-processing code that doesn't respond to events, but performs the specific work you need your application to perform.


Not everything in this hour's lesson will be applicable right away. Keep in mind that this lesson is a preview of details to come, especially in this and the next part of this tutorial where you'll learn language specifics.

Projects In Depth

An application consists of a single project. No application will contain multiple projects, because a project is a single application's collection of files that work together. (No project will contain multiple applications, either; Visual Basic maintains the one project/one application relationship.) Table 6.1 describes the kinds of files that can appear in a project.

Table 6.1 The Files That Make Up Projects

File

Extension

Description

ActiveX

OCX

Appears if your application contains

control

ActiveX controls.

Class

CLS

Appears if your application contains a class (a description of a user-generated Visual Basic object). Hour 20's lesson explains more about classes.

Project

VBP

A record-keeping file that maintains the project contents. Visual Basic updates this file for you and displays its contents in the Project window.

Form

FRM

A form description file.

Form

FRX

Contains the control properties that

properties

appear on the form.

Resource

RES

A file that holds the application's resources, such as the menus, icons, and accelerator keys.

Standard

BAS

A file that holds non-event procedure

module

code.


A single project may contain multiple form files, form properties files, standard modules, class modules, and ActiveX control files.

The Project window constantly updates as you add and remove files to your applications. It lets you navigate your projects by selecting the file that you want to work with. The Project window, such as the one in Figure 6.1, displays your project files by using an Explorer-like format, with folders and icons that represent the different kinds of files available in the Project window.

Figure 6.1

A Project window can contain several files.


Often, Visual Basic programmers call the Project window the "Project Explorer" due to the interface it shares with Windows Explorer.

When you want to work on a Visual Basic application, you'll open the project file to gain access to the project's components. When you save the project, you save every file in the project. If you want to edit a component, such as the form inside the Form window, double-click the form to open it for editing.

From the Project menu choose <project name> Properties to display Figure 6.2's Project Properties dialog box. From this dialog box, you can specify the startup file (usually, but not always, the application's primary form is the startup file specified in the option labeled Startup Object), compile options, and version control if you want to maintain different running versions of an application.

Figure 6.2

Customize the project from the Project Properties dialog box.

As you begin creating more advanced Visual Basic applications, you'll work as much or more within modules (some applications have several code modules) as you do with controls on the form. You'll begin to add code to your application's modules so that the application can work with general-purpose code that often works with the form controls.


All event procedure code resides in a module called the form module, as you'll see in the following example section. Event procedures aren't the only kind of code that can appear in a form module. You can also write general procedures that work with the event procedures.

For example, if you want several different controls to respond in much the same manner, you could type common code inside each event procedure. If you add a general procedure to the code module, however, you can put the common code inside the general procedure. Each event procedure can then trigger the general procedure's code (by using a method known as calling the procedure). When the general procedure's code completes, Visual Basic returns control back to the event to clean up anything that's left and to close the event procedure. The general procedure acts as a detour for the event procedure's code.


By putting common code in a module's general procedures, rather than duplicate the code throughout your event procedures, you need to change the code in only one location if the application's goal changes. On the other hand, you would have to change every occurrence of the code if you kept multiple copies of the code throughout several event procedures.

Example

This topic section has been loosely discussing modules. Now is a good time to learn about the different kinds of modules that you can write.

Visual Basic supports these three kinds of modules:

All the code you've seen so far in this book--the event procedure code--has resided inside a form module. A form module's code goes with the form. Therefore, if your application contains several forms, your application will contain several form modules. The form modules contain event procedures related to its form's controls. As you've learned in this topic section, a form module might contain code inside a general procedure as well as in event procedures.

A form module not only contains event procedures, but also general procedures and possibly class procedures. Also, a form module can contain data declarations. Figure 6.3 shows a form module's makeup. A general procedure contains many of the same kinds of code details that an event procedure contains and even includes parentheses after its name.

Figure 6.3

A form module contains event procedures, general procedures, class procedures, and a Declarations section.

You'll write general procedures when your program needs them, so you're responsible for naming them. Unlike event procedures, general procedures don't follow any preset naming pattern. General procedures appear with the declarations in a module section named General. All these sections (such as Declarations and General) appear in the Code window, as you'll see in the third topic's "Next Step" section at the end of this lesson.


Keep the Visual Basic overall picture in sight here. The rest of the book discusses the nitty-gritty details of the code lines that reside inside these procedures and declaration areas. This hour's topic is clearing the way for the details so that you know how code fits together.

Hour 20's lesson, "Classes and the Object Browser," explains class procedures. You can write advanced, fully working Visual Basic applications without using class procedures, so their coverage isn't critical at this time.

Next Step

The form procedures, general procedures, and class procedures that you studied in the preceding example section included a section named Declarations. The Declarations section of any module holds data descriptions that belong only to that module. The procedure's data is said to be local to the procedure. Therefore, if you declare data-holding areas (called variables, as you'll see in Hour 7) in one form module's Declarations section, only the procedures inside that form module can store and access the data locations.

If your application contains several forms and, thus, several form modules, one form module can't access the data in another form module unless you make specific arrangements to share the data, as you'll learn to do throughout this course.


All modules have one Declarations area each but can contain multiple procedures of every kind.

A standard module looks a lot like a form module. Standard modules are separate files within your application's project (with the .bas extension) that contain code. Standard modules have no event procedures, but they have a section named General that holds a Declarations section and procedures that you write. You'll see throughout this tutorial how to use a standard module to hold processing code that applies to multiple forms. Whereas code inside one form module can't easily access variable data in another form module, a standard module's code can access all form variable information within your complete application.


As you work more with Visual Basic, remember that a standard module doesn't have to be tied to any one application. Suppose that you produce some accounting calculations that you want to use in several applications. Put those accounting calculations inside a standard module. You can then add that module (by using the Project menu's Add Module option) to any application that needs to access the accounting routines. Of course, you'll want to keep specific form and control names out of such standard modules that you use across applications; otherwise, the standard module will work only with a single application.

To look at a fairly comprehensive project that includes all three kinds of modules, follow these steps:

  1. Open Visual Basic's sample application named Progwob (stored in the \Samples\PGuide\ProgWOB directory folder).
  2. Double-click the Project window to expand it to your entire editing area. The Project window displays forms (which each contain form modules to hold the event procedures for the form controls), standard modules (listed in the Modules folder), and class modules.
  3. Open each folder by clicking the plus sign next to each one. After you adjust the bottom edge of the Project window, you'll see all the forms and modules shown in Figure 6.4.

Figure 6.4

You can display objects within different modules.

  1. Now that you've seen the large Project window, double-click the window's title bar again to resize the window to a smaller size.
  2. Drag the Project window to the right edge of your screen to make room for the Code window.
  3. Double-click the form named frmImplements to select and display it.
  4. From the View menu choose Code. Visual Basic displays the selected form's Code window. A lot of code goes with the form, so you'll see lots of procedures. The editor automatically separates procedures from each other by using dividing lines.
  5. Although you can scroll through the Code window, Visual Basic's editor is smart; the two drop-down list boxes at the top of the Code window search and find specific procedures for you. The left drop-down list describes an object, whereas the right drop-down list describes procedures. The General object contains the Declarations section and any general procedures that appear in the form module. Open the right drop-down list, as shown in Figure 6.5, to see a list of the Declarations section and the general procedures. You won't see event procedures in this list.

Figure 6.5

This drop-down list shows your form module's Declarations and general procedures.

  1. Select the General object's procedure that you want to view

  2. Select Declarations from the list to move the text cursor to that area in the form module. Nothing seems to happen, but as you'll see, Visual Basic moves the text cursor to the top of the form module to the Option Explicit statement. All code in that section (down to the first dividing line) is part of the Declarations section that applies to the entire form module.
  3. Select NewShapes from the list now. The Visual Basic Code window jumps to the subroutine general procedure named NewShapes. (Although you could have scrolled down to the procedure, can't you see how selecting the procedure is easier?) NewShapes is a general procedure, and you know that because it's listed in the General object section.
  4. Click the arrow next to the Object drop-down list (on the left) to open the list of form module objects that appear in the form module. Figure 6.6 shows this list.

Figure 6.6

This drop-down list shows your form module's General section and the form's objects.

  1. You already know what the General section contains, so select cmdLate from the list. As you can tell from the name, cmdLate is a command button on the form. As soon as you select cmdLate, Visual Basic updates the procedure drop-down list on the right to contain only those procedures related to the cmdLate object.
  2. Scroll through the procedure list. You'll see that Visual Basic boldfaces only the Click event in the list. The list contains all possible events for command buttons. Visual Basic boldfaces Click to tell you that only the command button's Click event has an event procedure.
  3. Select the Click event; Visual Basic displays the rather lengthy cmdLate_Click () event procedure. As you can see, the two drop-down lists let you select the Declarations section and the general procedures (both in the General object section), as well as the event procedures that are available for the control objects on the form.
  4. Double-click the Project window's modFriends entry to display the standard module named modFriends in the Code window. If you click the object drop-down list, you'll see only a General section. Why? Remember that a standard module never contains event procedures, but only a Declarations section and standard procedures that aren't tied to any event.
  5. Open the procedure drop-down list to see all the general procedures in the module (including the Declarations section).
  6. Scroll through the procedures and close the application when you're finished. You now should have a better idea of Visual Basic's Code window capability to display event procedures, Declarations, and general procedures.

If you click the Code window's Procedure View button on the bottom left, Visual Basic displays only the selected procedure. If you click the default Full Module View button, Visual Basic displays the list of procedures separated by the dividing lines. Because you can display whatever procedure you want to see and edit with the drop-down list boxes, the Procedure View button keeps the other procedures out of your way.

Topic 2: Program Documentation

Visual Basic totally ignores the most important statement you'll write: remarks. Remarks provide program documentation for the programmer. Remember that you write a program once but read, maintain, and update that program many times. The easier you make it to understand the program code you write, the easier it will be for you to understand that code later when you have to make changes. As you write, you'll want to embed program documentation by using Visual Basic remarks. In this topic section, you'll learn how to code remark statements and document your code.

Overview

When you add program documentation, you're telling yourself--and anyone else who might work on your program in the future--about the program details. Although any Visual Basic programmer can scan Visual Basic code and decipher the details, remarks will speed and simplify that understanding because you write remarks by using the same language you speak with.

The Need for Remarks

You know that a program exists to give the computer instructions to read and follow. You need to understand the programs you write, however. After writing a program, you can't always remember parts of the program when you're making changes later. When someone else writes a program, working on that program is especially difficult.

Someday, computer instructions might be written in a spoken language such as English. Until then, you must learn to speak and understand the computer's language.

The Remark Statement's Format

The Rem statement makes Visual Basic code more understandable to humans, although the computer ignores Rem. Rem is short for remark. The format of the Rem statement is

Rem Any message you choose

You can have as many remarks in your program as you want. Many programmers scatter remarks throughout a program. You can insert remarks in event procedures, general procedures, declarations sections, and class procedures. The computer completely ignores remarks. Remarks produce no output, store no data, and require no data.

If a computer completely ignores remarks, you probably wonder why you should bother to use them. Rem statements are for people to use so that they can understand programs better. For example, a Visual Basic program that produces a fancy colored box with flashing lights around it and your name inside (like a marquee) would take some cryptic Visual Basic graphic and text commands. Before those commands, you might put a remark like this:

Rem The next few lines draw a fancy colorful boxed name

This remark doesn't tell Visual Basic to do anything, but it makes the next few lines of code more understandable to you and others; this statement explains--in your own language, not in Visual Basic--exactly what the program is going to do.

Rem statements also are helpful for putting the programmer's name at the top of a program. In a large company with several programmers, it's helpful to know who to contact if you need help changing the programmer's original code. Remember that Rem doesn't display that name on the form or anywhere else when you run the program (printing is done with other Visual Basic commands), but the name is there for anyone looking at the program's listing.

You also might consider putting the module file name of the program in an early Rem statement. For example, the statement

Rem Programmer: Pat Johnson, Module: ComputeSales.BAS ()

tells who the programmer is, as well as the program's module file name. When you're looking through many printed program listings, you quickly can load the one you want to change with Visual Basic's editing tool by looking at the Rems at the top of the program.

Rem's Shortcut: The Apostrophe

Because Rem statements appear so often in programs, the authors of Visual Basic supplied an abbreviation for the Rem statement. Rather than type Rem, you can type an apostrophe, ', and Visual Basic interprets the line as a remark. Unlike Rem, apostrophe remarks can appear to the right of program lines to help explain each line. Rem statements have to go on separate lines.

The following two lines are identical:

Rem This is a remark

' This is a remark

Using Helpful Remarks

Although a program without remarks can be difficult to understand, you should use only helpful remarks. Remarks explain what the program code is doing. Therefore, the following remark isn't helpful:

' Put the value 3 into the variable named intNumKids

intNumKids = 3

Although the preceding remark is lengthy, it doesn't explain why the value 3 is placed in the statement. Consider the following improved example:

' Save the number of kids for dependent calculations

intNumKids = 3

This remark gives a better idea of what the program's statement (the assignment) is used for. Someone trying to figure out the program would appreciate the second remark more than the first remark.

This example was simple. However, many Visual Basic statements don't require remarks. For example, including a remark to explain the End statement might not be worth much because there's little ambiguity about what's going on; End terminates the running application.

Remember to put remarks in your programs as you write them. You're most familiar with your program logic when you're typing the program in the editor. Some people put off including remarks in their programs until after they write the programs. As a result, the remarks never get included, or the programmer makes only a half-hearted attempt to include them.

Most of this tutorial's examples include remarks that explain the code.


Visual Basic lets you to insert blank lines in your code to separate sections of code from each other. Visual Basic programs are also known as free-form, meaning that statements can begin in any column. Most Visual Basic programmers include lots of white space (blank lines and extra spacing here and there) to make programs more readable than they would be if the code were scrunched together.

Example

Suppose that you write several standard accounting procedures that you want to use in different applications. Here's a great introductory remark that you can place in the standard module's Declarations section (the Declarations section always appears before any procedures):

'''''''''''''''''''''''''''''''''''''''''''''''''''''

'                UTILITY FUNCTIONS                  '

'                                                   '

' This module contains useful functions that you    '

' can use in expressions on your forms and reports. '

'''''''''''''''''''''''''''''''''''''''''''''''''''''

The apostrophe looks cleaner and is easier to type than a bunch of Rem statements.

The following section of code contains remarks that appear on lines by themselves, as well as to the right of other programming statements:

For intPtr = 1 To Len(strAString)   ' Go through string char by char

   strCurrChar = Mid$(strAString, intPtr, 1) 'Get the current character.

   Select Case strPrevchar         'If previous char is a letter

                                   'this char should be lowercase.

Because the apostrophe is easier to type and can be used where Rem can't be used, the rest of this tutorial uses the apostrophe remark rather than Rem.

Next Step

Sometimes you may write code but you want to temporarily block that code from executing. Rather than delete lines of code that you'll have to add later, insert the apostrophe remark before each line. The next time you run the program, Visual Basic will ignore that section of code. When you're ready for the code to execute properly, remove the remarks, and the lines will execute again. Remember again that Visual Basic ignores all remarks, even if those remarks contain valid Visual Basic code, so remarking out code lets you modify the execution of the program.

Topic 3: Code Window Extras

Hour 7's lesson begins diving head first into Visual Basic program code. Therefore, this hour's lesson wraps up with a few Code window features that you should learn now so you can implement them as you write code for your applications.

Overview

With each version of Visual Basic, Microsoft has improved Visual Basic's features, commands, and development environment. With version 5, Microsoft made some of the most significant Code window improvements since Visual Basic's inception. You've already seen how Visual Basic can pop up event lists when you type control names followed by a period so that you can select from the list rather than have to type the control name. The Code window sports many additional features. Some of them you won't be able to learn until you get to certain programming topics later in this course; you can master a few extras in the Code window now to speed your code entry later.

Multiple Code Windows

If your application contains multiple modules, you can open multiple Code windows for each module. Therefore, you can view and edit your form's event procedures at the same time you view and edit your standard module's Declarations section.

The multiple Code windows let you edit more than one module's procedure at once. Perhaps you can resize the two Code windows on your screen to see both at once. You can easily copy and move text between the two windows, and you don't have to close one when you want to make a minor change to another module.

Set the Editor Options

Figure 6.7 shows the Options dialog box (choose Options Editor from the Tools menu). As you work with the Visual Basic editor, you'll return to this dialog box to modify the way the editor behaves. Especially if you're new to Visual Basic, you'll want to try some of the options to see which ones fit well within your programming abilities and which detract from writing code.

Figure 6.7

You can set several Code window editor options.

Table 6.2 describes the options you can turn on or off with the editor options dialog box.

Table 6.2 The Editor Options You Can Control

Option

Description

Auto Syntax Check

Checks your code as you type it and indicates an error in Visual Basic language spelling or grammar (called syntax) while you're typing rather than wait until you run the program.

Require Variable Declaration

Requires that you first tell Visual Basic about all storage locations before you use them (discussed in depth in Hour 7's lesson).

Auto List Members

Lets Visual Basic display the pop-up list of items (such as control events) that can complete the statement you're starting to type. Rather than type the rest of the command or statement, you can select from a list of choices.

Auto Quick Info

Displays pop-up help automatically that shows you the format of lengthy code you're about to enter.

Auto Data Tips

Used during debugging to show the value of storage locations you're pointing to with your mouse.

Auto Indent

Automatically indents your code to align with the previous line to eliminate pressing Tab for subsequent code lines.

Tab Width

Lets you specify exactly how many spaces the Code window's editor should insert when you press Tab.

Drag-and-Drop

Lets you drag and drop objects from elsewhere

Text Editing

in the development environment into your code.

Default to Full Module View

Sets the default to show the full module's procedures or just one section at a time.

Procedure Separator

Lets you display or hide the separator lines that divide procedures from one another when viewing the full module.

Example

Open the ProgWOB sample project that you opened in this lesson's first topic section. Open the Project window if it's not already open, and then open the Forms folder to display all the forms. In this short example, you're going to open two Code windows at once to see how easy Visual Basic editing can be.

Double-click the form named frmEvents to display the form. From the View menu choose Code to see the code in the form module. Now, double-click the form named frmSticks to display that form and choose View Code. At first, it appears that Visual Basic closed the first Code window when you opened the second window, but if you pull down the Window menu, you'll see two sets of code: one for the frmEvents code and one for the frmSticks code.

Click the Code window's Restore button (the center button to the far right of the menu bar). Visual Basic resizes all the open windows, as shown in Figure 6.8.

Figure 6.8

Working with multiple Code windows.

After you resize and move the Code windows, you can position both open Code windows so that you can see both sets of code at once. (You can click each Form window close button to close the Form windows, because they will probably get in your way.) Clicking in one window and then the other moves the text cursor to the next window, and activates that window for data entry. You now can work within one Code window and view code within the other for reference, or you can use the Windows Clipboard to copy and move code between the windows.


If you make changes with the code, do not save anything when you close Visual Basic or attempt to open another project. If you inadvertently type something over a sample application, you'll have to reinstall the samples from Visual Basic's installation CD-ROM.

Next Step

Scroll through the code windows that you've got open from the last example. Study the way the Visual Basic programmers used remarks. You won't see the Rem statement because most programmers use the shorter apostrophe remark. Also, the apostrophe is cleaner and lets the programmer add remarks to the right of existing lines of code.

Do you notice something about the colors inside the Code window? The remark color varies from the other code. Some code is black (variable, control, and procedure names), some is green (remarks), and some is blue (reserved keywords). The colors give you clues to the type of code you're typing. As you press Enter after typing a line, Visual Basic colors the code according to a present plan. For example, if your remarks appear in green, you'll get used to seeing green remarks. If you type a remark but Visual Basic doesn't color the remark green by the time you get to the next line, you'll have a good idea that you did something wrong, such as omitting the apostrophe.

Summary

This hour's lesson completes this first part of your Visual Basic night schooling. You've seen an introduction to Visual Basic, created simple applications, placed controls, set properties, and now understand more about how code fits into the Visual Basic picture.

This hour's lesson shed some needed light on Visual Basic code. You learned that not every application contains the same sets of code. Some applications contain form modules, whereas others contain two other modules--a standard module and a class module. A standard module often resides in several applications because of the common code you can put there.

Not only should you worry about your code's content, but also the code's documentation. Be sure to add remarks throughout your code, describing the code's duties along the way. The Declarations section (always the first section of any module) is a great place to put a remark with your name, so someone can contact you later if they have questions about the program you wrote.

In Hour 7, you'll begin learning more of the Visual Basic language so that you can begin to add power to your programs.

Hour 6 Quiz

  1. True or false: You'll find Visual Basic code in event procedures and general procedures.
  2. True or false: General procedures contain no event procedure code.
  3. True or false: A form module contains only form design contents and controls but no code.
  4. What kind of code can you put in a standard module?
  5. What specific application code is the Declarations section available to?
  6. What object name do you see in the Code window when you display the Declarations section?
  7. Why does Visual Basic not boldface every event in the procedures drop-down list?
  8. What are the two kinds of remark statements? Why would a programmer use one over the other?
  9. What do the Code window's two drop-down list boxes do?
  10. Name one advantage of multiple Code windows.

Hour 6 Homework Exercises

  1. Open the Code window for one of the sample applications. Look at the class module to see whether you see differences between it and the form module. (Some sample applications don't have class modules.) Find three sequential lines that contain no remarks but contain executable code. Turn these lines into remarks with three apostrophes. (Don't save the file if it's a sample file.)
  2. Click the Code window's view buttons to see the difference between the Full Module View and the Procedure View. From the Full Module View, scroll through the entire module. If the module is lengthy, you'll see why most Visual Basic programmers select code sections that they want to work on from the procedures' drop-down list box.

© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.