There's more to Visual Basic programs than forms, visual controls, and
code. Often, you'll include messages called remarks within your programs that Visual Basic, Windows, and your computer completely ignore. The remarks aren't for the computer
but they are for programmers.
At other times, you'll need to
display messages to users and get answers from users, and no kind of control or Visual Basic object works better than message boxes and input boxes. This unit teaches you how to display and manage message
boxes and input boxes. You'll learn
how and when message and input boxes work more effectively than labels and text box controls.
Concept: Remarks help both you and other programmers who might modify and update your Visual Basic applications in the future. Remarks offer descriptive messages that explain in English (or whatever language
you
prefer) what's going on in the program's event procedures.
It's said that a program is written once and read many times. That saying is true because of the nature of applications. Often, you'll write a program that helps you or your business
compute required calculations and keep track of daily transactions.
Over time, requirements change. Businesses buy and sell other businesses, the government changes its reporting and taxing requirements, and people's needs change. You should realize that,
after you write and implement a program, you'll make modifications
to that program later. If you use the program in a business, you'll almost certainly make many modifications to the program to reflect changing conditions.
Definition: Program maintenance refers to the modification of programs over time.
Note: If you program for someone else, the chances are high that others will modify the programs that you write and that you'll modify programs that other programmers write. Therefore, as you write programs, think about the future maintenance that you and others will make. Write your programs clearly, using ample spacing and indention, and add remarks that explain difficult sections of code.
A remark is a message that you
put inside a program's code. Programmers concerned about maintenance know that ample remarks help clarify code and aid future maintenance. Visual Basic completely ignores any and all remarks because those remarks
are for people looking at your program
code. Users don't see remarks because users don't see the program's code; rather, users see a program's output.
Programmers often add remarks to their programs for the following purposes:
Note: Even if you write programs for yourself, and if you are the only one who will modify your programs, you should still add remarks to your program! Weeks or months after you write a program, you'll have forgotten the exact details of the program and remarks that you interspersed throughout the code will simplify your maintenance and will help you find the code that you need to change.
Tip: Add remarks as you write your programs. Often, programmers will say to themselves, "I'll finish the program and add remarks later." Trust methe remarks don't get added. It's only later, when programmers need to modify the program, that they notice the lack of remarksand regret it.
Review: Add remarks to your program so that you and others can more quickly grasp the nature of
the program and can make modifications to it more easily when needed.
Concept:
Visual Basic supports several remark formats. Unlike some other programming languages, Visual Basic remarks are easy to add to your code, and their free-form nature enables you to add remarks whenever
and wherever needed.
Visual
Basic supports the following two kinds of remarks:
The Rem statement is more limiting than the apostrophe and
isn't as easy to use as apostrophes. Nevertheless, you'll run across programs that use Rem statements, so you should learn how Rem works. Here is the format of the Rem statement:
Rem The remark's text
You can put anything you want in place of The remark's text. Therefore, all of the following are remarks:
Rem Programmer: Bob Enyart, Date: Mar-27-1996 Rem This program supports the check-in and check-out Rem process for the dry-cleaning business. Rem This event procedure executes when the user Rem clicks on the Exit command button. When pressed, Rem this event procedure closes the program's data Rem files, prints an exception report, and terminates Rem the application
The first of these remark sections consists of a one-line remark that tells the programmer's name and the date that the program was last modified. If someone else must modify the program later, that person can find the
original programmer if needed to
ask questions about the program's code. The second remark describes the overall program's goal by stating with a high-level description the program's purpose. The third remark might appear at the top of a command button's
Click event procedure.
As you can see, you can add one or more lines of remarks depending on the amount of description needed at that point in the program. Visual Basic ignores all lines that begin with Rem. When someone looks at the program code
later, that person will know
who the programmer is, the date that the program was written, the overall purpose of the program, and the overall description of each procedure that includes a remark section.
Say that you used apostrophes in place
of the Rem statement in the previous remarks. The following rewritten remarks demonstrate that the remarks are even more effective because Rem doesn't get in the way of the remark's text:
' Programmer: Bob Enyart, Date: Mar-27-1996 ' This program supports the check-in and check-out ' process for the dry-cleaning business. ' This event procedure executes when the user ' clicks on the Exit command button. When pressed, ' this event procedure closes the program's data ' files, prints an exception report, and terminates ' the application
The remarks don't have to go at the beginning of event procedures. You can place remarks between lines of code, as done here:
Dim Rec As Integer Rem Step through each customer record For Rec = 1 To NumCusts ' Test for a high balance If custBal(Rec) > 5000 Then Call PayReq End If Next Rec
Note: Don't try to understand the details of this code yet. Concentrate now on the remarks. The code contains some advanced features (Visual Basic arrays and subroutine procedures) that you'll learn about in the last half of this book.
The apostrophe remark offers another advantage over using Rem because you can place apostrophe remarks at the end of Visual Basic statements. By placing a remark to the right of
certain lines of code, you can clarify the purpose of the code. Consider
how the following code section uses remarks to explain specific lines of code:
a = 3.14159 * r ^ r ' Calculate a circle's area
Perhaps only a mathematician could interpret the formula without the remark. The remark helps even nonmathematicians understand the purpose of the statement. There is no reason that you should have to reexamine code every time you look at code. By
reading remarks, you can gleam the code's purpose without taking the time to interpret the Visual Basic code.
The wrong kind of remarks won't help clarify code, though, so don't overdo remarks. As a matter of fact, lots of lines of code need no
remarks to explain their purpose. The following remark is redundant and wastes both your programming time and anyone's
who may maintain the program later:
Dim Sales As Single ' Define a variable named Sales
Stop and Type: Listing 9.1 contains a Select Case routine that you saw in Listing 8.5 of the previous unit. This code contains remarks that help clarify the purpose of the code.
Review: Add remarks throughout a Visual Basic program, using either the Rem statement or the apostrophe, to tell other programmers as well as yourself what the program is doing. Add the remarks as you write the
program so that the remarks will be up to date and always reflect your intent.
1: Rem The following Select Case to End Select code 2: Rem assigns a student's grade and school name 3: Rem to the label on the form. The code checks 4: Rem to make sure that the student is not too 5: Rem young to be going to school. 6: Select Case Age 7: ' Check for too young... 8: Case Is <5: lblTitle.Text = "Too young" 9: ' Five-year olds are next assigned 10: Case 5: lblTitle.Text = "Kindergarten" 11: ' Six to eleven... 12: Case 6 To 11: lblTitle.Text = "Elementary" 13: lblSchool.Text = "Lincoln" 14: ' Twelve to fifteen... 15: Case 12 To 15: lblTitle.Text = "Intermediate" 16: lblSchool.Text = "Washington" 17: ' Sixteen to eighteen 18: Case 16 To 18: lblTitle.Text = "High School" 19: lblSchool.Text = "Betsy Ross" 20: ' Everyone else must go to college 21: Case Else: lblTitle.Text = "College" 22: lblSchool.Text = "University" 23: End Select
Analysis: Indention was used in Listing 9.1's remarks to put the remarks where they would be most effective. The
remarks on lines 7, 9, 11, 14, 17, and 20 don't appear at the end of their respective code lines
because the remarks would hang too far out to the right and would not fit in the Code window. Nevertheless, the remarks do clarify each Case in the sequence.
Notice that the first few lines, 1 through 5, give an overall descriptive account of the code that
follows.
Definition: Message boxes perform specialized program output.
There will be many times
in programs when you'll need to ask the user questions or display error messages and advice to the user. Often, the controls on the form won't work well for such dialogs. For example, in the Lesson 4's project, the user had to
enter 0 through 4 when asked
for a discount percentage code. If the user entered an incorrect code, the program beeped and erased the user's bad entry, but the program didn't tell the user why the entry was a mistake. Users don't always know what's
expected of them. The user would be
helped much more by seeing an error message, such as the one shown in Figure 9.1, before the program cleared the user's incorrect entry.
Figure 9.1. A message box can provide the user with helpful information.
Note: Message boxes aren't controls. Unlike controls that stay on the form throughout a program's entire execution cycle, a message box pops up on top of the form and disappears when the user responds to the message box, usually by clicking the message box's OK command button.
There are two ways to produce message boxes. You can use the MsgBox statement or the MsgBox()
function. You've seen one built-in function before, Val(), which converts a string of digits to a number. Visual Basic includes several built-in functions;
you'll learn many of them in Lesson 7, "Functions and Dates." Until Lesson 7, however,
you need to learn a few of the functions such as Val() and MsgBox(), because they help you work with the commands that come before Lesson 7. The choice of
using the MsgBox statement or the MsgBox() function depends on the response that you need the user
to make to the display of the message box.
Definition: Input boxes perform specialized program input.
The text box
controls that you've seen are great for getting values from the user. Other controls that you'll learn as you progress through this book also accept the user's input from the keyboard or mouse. Nevertheless, Visual Basic's controls just
aren't enough to
handle all the input that your program will need. Input boxes are great to use when the user must respond to certain kinds of questions. Text boxes and other controls are fine for getting fixed input from the user, such as data values with
which the
program will compute. Input boxes are great for asking the user questions that arise only under certain conditions. Input boxes always give the user a place to respond with an answer. In Figure 9.2, the input box is asking the user for a title
that will
go at the top of a printed report listing.
Figure 9.2. Use input boxes to request information.
Note that there is more than one way for the user to respond to Figure 9.2's input box. The user can answer
the question by typing the title at the bottom of the input box and pressing Enter or clicking the OK command button. The user also can click the
Cancel command button whether or not the user entered a title. Therefore, the program must be capable of
reading the user's entered answer as well as responding to a Cancel command button press. Responding to message box and input box command buttons is
part of the processing that you'll learn about in the remaining sections of this chapter.
Review: Message boxes display output and input boxes get input. The message and input boxes offer ways for your programs to request information that regular controls can't handle. Use controls to display and
get data
values that are always needed. Use message and input boxes to display messages and get answers that the program needs in special cases, such as for error conditions and exception handling.
Concept: The MsgBox statement displays messages for the user. In addition, the MsgBox() function displays
messages but also provides a way for your program to display and check for multiple command button
clicks on the message box window. This section explains how to use the MsgBox statement.
All message boxes displayed with the MsgBox statement
display an OK command button. The command button gives the user a chance to read the message. When the user has finished reading the message, the user can click OK to get rid of the message box. Your
program suspends execution during the reading of the
message box. Therefore, the statement following the MsgBox statement executes when the user clicks OK.
Here is the format of the MsgBox statement:
MsgBox msg [, [type] [, title]]
The msg is a string (either variable or a string constant enclosed in quotation marks) and forms the text of the message displayed in the message box. The type is an optional numeric value or expression that
describes the options you want
in the message box. Figure 9.3 shows which icons you can place in a message box (Visual Basic displays no icon if you don't specify a type value). The title is an optional string that represents the text in the
message box's title bar. If you
omit the title, Visual Basic uses the project's name for the message box's title bar text.
Figure 9.3. The icons that you can display in a message box.
Definition: Modality determines whether the user or system responds to a message box.
The options that you select, using the type
value in the MsgBox statement, determine whether the message box displays an icon as well as controls the modality of the message box. Table 9.1 contains the code values that you'll use to form the
MsgBox type value.
Value | CONSTANT.TXT Value | Description |
16 | MB_ICONSTOP | Displays the stop sign icon |
32 | MB_ICONQUESTION | Displays the question mark icon |
48 | MB_ICONEXCLAMATION | Displays the exclamation icon |
64 | MB_ICONINFORMATION | Displays the lowercase i (meaning information) icon |
4096 | MB_SYSTEMMODAL | The user's application is system modal, meaning that the message box must be handled before you can switch to any other Windows program |
The modality often causes confusion. If you don't specify the system model type value of 4096 (or if you don't use
CONSTANT.TXT's MB_SYSTEMMODAL named constant to specify the system's modal mode), the user's application won't continue
until the user closes the message box, but the user can switch to another Windows program by pressing Alt+Tab or by switching to
another program using the application's control menu. If, however, you do specify that the message box is system modal,
the user won't able to switch to another Windows program until the user responds to the message box, because the message box will have
full control of the system. Reserve the system modal message boxes for serious error messages that the user must
read and respond to before continuing with the program.
Note: If you don't specify an icon, Visual Basic doesn't display an icon. If you don't specify the system modality, Visual Basic assumes that you want an application modal message box.
Stop and Type: Listing 9.2 ought to answer questions that you have about message boxes. The listing contains a series of message box statements. Each statement displays a different message box and each message
box is
different.
Review: Use the MsgBox statement to display messages, such as error messages, to the user. The message boxes will contain an OK button that the user clicks to close the message box. Depending
on whether you
specify a type value, the message box might contain an icon as well as be system modal. If you specify a third title value, the message box's title bar will contain the text of the title you request.
Listing 9.2. Displaying different message boxes.
1: ' A simple message box with a message and no icon 2: MsgBox "Just a message" 3: ' A message box with the stop sign icon 4: MsgBox "Stop in the name of love", MB_ICONSTOP 5: ' A message box with the question mark icon 6: MsgBox "Did you turn on the printer?", MB_ICONQUESTION 7: ' A message box with the exclamation icon 8: MsgBox "Don't forget to exit!", MB_ICONEXCLAMATION 9: ' A message box with the "i" information icon as 10: ' well as a title that's not the project name 11: MsgBox "A byte is 8 bits", MB_ICONINFORMATION, "A title" 12: ' A message box that is system modal 13: MsgBox "You cannot switch programs", MB_SYSTEMMODAL 14: ' A message box with a question mark icon, a system modal setting, 15: ' and a title of Title 16: MsgBox "Info icon, system modal, and a title", MB_ICONQUESTION + MB_SYSTEMMODAL, "Title"
[ic:Output]Listing 9.2 demonstrates several different kinds of message boxes. Assuming that the project name is PROJECT1.MAK, Figure 9.4 shows the simple message that appears from line
2's MsgBox statement.
Figure 9.4. A simple message box with no icon or given title.
Analysis: Note that there is no icon because line 2 doesn't contain a
type value. Also, the message box's title is Project1 because the project's name is PROJECT1.MAK and the MsgBox statement doesn't
specify a different title. The message box also is application modal. The user must respond to the message before
continuing with the program. The user can switch to another Windows program, however, by pressing Alt+Tab, or Alt+spacebar, or by selecting
from the control menu.
Line 4's MsgBox statement displays a stop sign icon to the left of the message.
Rather than use the CONSTANT.TXT named constant, you can type 16 for the type value.
Line 6's MsgBox statement displays a question mark icon to the left of the message. Line 8's MsgBox statement displays an exclamation point icon to the
left of the message.
Line 11 displays a message as well as the information icon. The information icon is a nice touch to add when offering advice to the user. Line 11 also displays a title in the message box's title bar. The title is simple: A
title.
Line 13's MsgBox produces a system modal message box. Line 14's MsgBox statement displays a message, an information icon, and a title, a title; this line is a system modal message box. Figure 9.5 shows Line 13's message box output.
Note: Note that Visual Basic expands or contracts the message boxes to hold the full text that you want to display.
Figure 9.5. A complete message box statement produces a message, icon, and title.
As you can see from Line 13's type value, you can add together an icon's value as well as the system modal value (or their
named constants, as done in Listing 9.2) to obtain both an icon as well as a system modal message box.
Tip: If you want to specify a title in a message box but not display an icon or change to system modality, insert two commas before the title string, as follows :
MsgBox "A byte is 8 bits", , "A title"
Concept: Use the MsgBox() function when you want the user to indicate a response to
the message in the message box. By using the MsgBox() function, you can display several different command buttons inside the
message box and determine which command button the user pressed so that you'll know how the user responded to the message.
Figure 9.6 shows a message box that looks a little different from the other ones that you've seen so far. Instead of a single OK command button, Figure 9.6's message box contains three command buttons. The MsgBox() function enables you to program
message boxes with multiple command buttons and then determine which command button the user pressed to close the message box.
Figure 9.6. Message boxes can have several command buttons.
The format of
the MsgBox() function is almost identical to that of the MsgBox statement. You must use the MsgBox() function differently from the statement, however. Always assign a MsgBox() function to a variable. Here is the format of the MsgBox()
function:
anIntVariable = MsgBox( msg [, [type] [, title]])
As you can see from the format, the MsgBox() function's format differs from the MsgBox statement in that you assign the MsgBox() function to an integer
variable that you've already defined. In addition, the MsgBox() function supports several more
type values than the MsgBox statement supported. Table 9.2 lists the MsgBox() function's type values along with their CONSTANT.TXT named constant
equivalents.
Value | CONSTANT.TXT Value | Description |
0 | MB_OK | The OK button appears only in the message box |
1 | MB_OKCANCEL | The OK and Cancel buttons appear |
2 | MB_ABORTRETRYIGNORE | The Abort, Retry, and Cancel buttons appear |
3 | MB_YESNOCANCEL | The Yes, No, and Cancel buttons appear |
4 | MB_YESNO | The Yes and No buttons appear |
5 | MB_RETRYCANCEL | The Retry and Cancel buttons appear |
16 | MB_ICONSTOP | Displays the stop sign icon |
32 | MB_ICONQUESTION | Displays the question mark icon |
48 | MB_ICONEXCLAMATION | Displays the exclamation icon |
64 | MB_ICONINFORMATION | Displays the lowercase i (meaning information) icon |
0 | MB_DEFBUTTON1 | The first button has the initial focus |
256 | MB_DEFBUTTON2 | The second button has the initial focus |
512 | MB_DEFBUTTON3 | The third button has the initial focus |
4096 | MB_SYSTEMMODAL system message | The user's application is modal, meaning that the box must be handled before you can switch to any other Windows program |
Here is the MsgBox() function that displayed the message box shown in
Figure 9.6:
BPress = MsgBox("Are you ready for the report?", MB_ICONQUESTION + MB_YESNOCANCEL, "Report Request")
The MB_ICONQUESTION named constant added to the MB_YESNOCANCEL
named constant produced both a question mark icon and the three buttons. A title also appeared due to the third value inside the MsgBox() function.
The reason that you assign MsgBox() functions to variables is so that you can tell what button the
user pressed. Suppose that the user pressed the Yes button in Figure 9.6. The program could then print the report. If, however, the user pressed the No
command button, the program could describe what the user needed to do to get ready for the report (load
paper, turn on the printer, and so on). If the user pressed the Cancel command button, the program would know that the user didn't want the report at
all. Of course, the application determines what set of command buttons will work best for any given
message box.
Table 9.3 lists the possible return values for the MsgBox() function. In other words, the integer variable will contain one of Table 9.3's values after every MsgBox() function completes. A subsequent If statement can then test to see
which command
button the user pressed.
Value | CONSTANT.TXT Value | Description |
1 | IDOK | The user pressed the OK button |
2 | IDCANCEL | The user pressed the Cancel button |
3 | IDABORT | The user pressed the Abort button |
4 | IDRETRY | The user pressed the Retry button |
5 | IDIGNORE | The user pressed the Ignore button |
6 | IDYES | The user pressed the Yes button |
7 | IDNO | The user pressed the No button |
Stop and Type: Listing 9.3 shows how you might handle the previous MsgBox() function that displayed the three-button message box in Figure 9.6. After the user clicks a button, the program can use If
statements to
determine which button the user pressed.
Listing 9.2. Displaying different message boxes.
1: BPress = MsgBox("Are you ready for the report?", MB_ICONQUESTION + MB_YESNOCANCEL, "Report Request") 2: ' Check the button pressed 3: Select BPress 4: Case IDCANCEL: lblPress.Text = "You pressed Cancel" 5: Case IDYES: lblPress.Text = "You pressed Yes" 6: Case IDNO: lblPress.Text = "You pressed No" 7: End Select
Analysis: Line 1 displays the message box and saves the button press in the variable named BPress. Line 3 begins a Select Case that assigns one of three
strings to labels on the form that match the user's
button press. This example is very simple; normally, you would perform one of several different kinds of routines, depending on which of the three buttons the user pressed.
There is no need to
code a Case Else statement because the three-button message box can return only one of the three values tested in Listing 9.2.
Concept: You'll find that the InputBox() function is easy because it acts a lot like the MsgBox() function. There are two InputBox() functions. The difference between
them lies in the type of data that each
returns. The InputBox() function receives answers that are more complete than the MsgBox() function can get. Whereas MsgBox() returns one of seven values that indicate the user's command button press, the InputBox()
function returns either a string or a
variant data value that holds the answer typed by the user.
There are two InputBox() functions. Here are the formats of the InputBox() functions:
aVariantVariable = InputBox( prompt [, [title] [, default][, xpos, ypos]]])
and
aStringVariable = InputBox$( prompt [, [title] [, default][, xpos, ypos]]])
The difference between the InputBox()
functions lies in the return value. The InputBox() function returns a variant data type and the InputBox$() function (notice the dollar sign) returns a string data type. Generally, the return type is not extremely
important. You'll almost always receive
the InputBox() answer in a string variable, and if you use the InputBox() function, Visual Basic converts variant data types to strings when needed.
The prompt works a lot like the msg value in a MsgBox() function. The user sees the
prompt inside the input box displayed on the screen. The title is the title inside the input box's title bar. default is a default
string value that Visual Basic displays for a default answer, and the user can accept the default
answer or change the default answer.
The xpos and ypos positions indicate the exact location where you want the input box to appear on the form. The xpos value holds the number of twips from the left edge of the form window
to the left edge of the input box. The
ypos value holds the number of twips from the top edge of the form window to the top edge of the input box. If you omit the xpos and ypos values, Visual Basic centers the message box on the form.
Note: Input boxes always contain an OK command button and a Cancel command button. If the user presses OK (or presses Enter, which selects OK by default), the answer in the input box is sent to the variable being assigned the returned value. If the user presses Cancel, a null string, "", returns from the InputBox() function.
Stop and
Type: The code in Listing 9.3 displays an input box that asks the user for a company name. The user either enters a response to the prompt or presses the Cancel command button to indicate that no
answer is coming.
Review: The InputBox() and InputBox$() functions get answers from users. You can offer a default answer that the user can accept or change. The input box functions return the answer into a string or variant
variable to
which you assign the function.
Listing 9.3. The input box asks the user questions.
1: Dim CompName As String 2: CompName = InputBox$("What is the name of the company?", "Company Request", "XYZ, Inc.") 3: If (CompName = "") Then 4: ' The user pressed Cancel 5: Beep 6: MsgBox "Thanks anyway" 7: Else 8: ' The user entered a company name 9: MsgBox "You entered " & CompName 10: End If
[ic:Output]Figure 9.7 contains the message box displayed from Listing 9.3.
Figure 9.7. Input boxes ask the users questions and return the answers.
Analysis: Listing 9.3 might be part of an event procedure that executes when the program is ready for a company name. Line 1 defines a string variable that holds the user's response. Line 2 contains the
InputBox$() function that asks for the company name and displays a default answer (automatically highlighted as shown at the bottom of Figure 9.7).
As soon as the user answers the input box request, Line 3 begins an if that checks for one of two
results: either the user pressed the Cancel button in response to the input box, or answered the input box by pressing OK. If the user pressed Cancel, the
input box function returns a null string, and lines 5 and 6 beep and display a message box thanking
the user for trying. Lines 8 and 9 restate the company name entered by the user.
Find the Bug
Write a command button Click routine that asks the user for his or her age. If the user presses Cancel, beep and display another message box saying, Thanks anyway. If the user enters
an age, use Val() to convert and store the age in a numeric variable
and then display the number of years until the user's retirement by subtracting the age from 65. Hint: The Str$() function performs the opposite of Val() and you can append the converted
number to another string to display the message. (Lesson 7 covers
Str$() in full detail.)