Hour 9


During this hour you will learn

Working with Interactive Keyboard and Screen I/O

This hour's lesson takes a break from the programming theory of the last few lessons. You're in for a treat. This lesson shows you how to program message boxes and input boxes. Message boxes let you display information for the user without changing the form on-screen. Input boxes let you get interactive user input without using a form's control. By saving the form controls for more standard I/O (input and output), your program can ask your user questions and display error messages using pop-up dialog boxes that users can control.

Tools such as message boxes and input boxes also will help you master the next few hours' lessons. By learning how to create and respond to message and input boxes, you can write small applications that test the programming controls that you learn in subsequent lessons.

Topic 1: The MsgBox() Function

You should be concerned with the way your output looks and also with the way users enter data. The MsgBox() function is one of the best ways to display a message for your users during the execution of the program. Unlike controls on a form, the message box that appears will pop up as a dialog box. After users read the message in the message box, they can click the message box's OK button and continue with the program.

FAST TRACK
Have you programmed in Microsoft Access or any other Windows-based programming environment? If so, you've no doubt used message boxes and input boxes, and this hour's lesson will be familiar to you. Visual Basic uses all the standard icons and responses you're used to. But even though you've seen message and input boxes before, you still need to read through this lesson to learn how the Visual Basic language hooks into these interactive dialog boxes.

Visual Basic uses internal functions to interact with users, and you need to familiarize yourself with Visual Basic's tables related to these I/O dialog boxes. When you learn how Visual Basic produces the boxes, including the named constants that Visual Basic uses to test users' return values from these dialog boxes, you can move onto Hour 10's lesson to learn how Visual Basic produces conditional control through If and related statements.

Microsoft wants you to begin using the MsgBox() function exclusively because the MsgBox statement doesn't let you test for button clicks.

Overview

The MsgBox() function not only displays data in a pop-up dialog box, but optionally displays an icon and response buttons for users. MsgBox() can write string data to the screen. The string contains the message you want to send to users.

Figure 9.1 shows a sample dialog box generated with MsgBox(). From the figure, you see that you control both the message and the title of the dialog box. You also can determine which icon is displayed and how many buttons appear on the box.

Figure 9.1

A message box is like a miniature dialog box.

Users can move or close message boxes but not resize them. This topic section explains how to display such message boxes. After you master message boxes, the next two topics build on that knowledge and show you two additional kinds of dialog boxes your user may need to see and respond to.

The MsgBox() Function

Although you won't fully master Visual Basic's predefined built-in functions until Hour 14's lesson, "Using the Supplied Functions," the message-box function (and its cousin, the input-box function) works so well and gives you so much to learn with that now is the best time to see how to work with those functions.


Just like a function procedure that you write, a built-in function always returns a value. MsgBox() is no exception. The second topic section explains how to work with MsgBox()'s returned value.

Here is the MsgBox() function's syntax:

intResponse = MsgBox(strPrompt [, intStyle] [, strTitle])

This hour's second topic explains how you work with the intResponse value, and you can ignore the value for this topic. You must include such an integer variable at the left of the MsgBox() function if you want the function to work correctly.

strPrompt is a string expression (a constant string enclosed in quotation marks, a string variable, or a text-control value) that you want displayed in the dialog box. If the string is long, the dialog box expands to hold the whole string, properly breaking each line between words. Figure 9.1's strPrompt would be "This is a message box".

The message box prompt can be no longer than 1,024 characters.

The last two values to the MsgBox() function are optional. The easiest kind of dialog box to display is one with only a message and an OK button. If you want to display such as message box, such as the one shown in Figure 9.2, you don't have to specify the second and third values. Whenever you see a statement or function format, such as the one shown at the beginning of this section for MsgBox(), the values inside brackets indicate optional values. Don't include the brackets; as part of the MsgBox() function's syntax, they simply indicate optional parts of the function.

Figure 9.2

Simple message boxes require only a prompt.


While you type inside Visual Basic's Code window, as soon as Visual Basic realizes that you're coding a MsgBox() function, VB pops up the Auto Quick Info help that describes the function's values for format. You can review the Auto Quick Info feature in Hour 6, "Understanding the VB Program Structure."

If you specify only a MsgBox() prompt string with no other values, Visual Basic displays the prompt and the project name in the message box's title bar. The following MsgBox() function displays Figure 9.2's message box:

i = MsgBox("This is a message box")

Assume that i is an integer variable that's been declared previously. As you can see, a simple message box that requires only that users click OK is simple to produce. When a program needs to display such a message, pop up a message box at the place in the code and users will get the message.

Extending Message Boxes

MsgBox()'s intStyle value is a numeric value or expression that controls the number of buttons as well as the icon that appear in the message box. strTitle is the string that appears at the top of the box in the title bar. (As mentioned earlier, if you don't specify a title, Visual Basic displays the project name for the message box title bar.)

The value you use for intStyle is made up of several things. Tables 9.1, 9.2, and 9.3 contain values that comprise intStyle. The tables include several named constants (sometimes called Named Constants), such as vbOKOnly. Visual Basic makes these named constants available to you from any procedure in any module, no matter how global or local the procedure is. Therefore, rather than code a 3 for the message box's style value, you can use vbYesNoCancel. Internally, vbYesNoCancel is set to a 3; however, vbYesNoCancel is easier for you to understand later if you have to change the program. vbYesNoCancel is self-documenting and tells you that the value means the three buttons (Yes, No, and Cancel) will appear in the message box.

Table 9.1 Controlling the Buttons

Named Constant

Value

Description

vbOKOnly 0

Displays OK button only

vbOKCancel 1

Displays OK and Cancel buttons

vbAbortRetryIgnore 2

Displays Abort, Retry, and Ignore buttons

vbYesNoCancel 3

Displays Yes, No, and Cancel buttons

vbYesNo 4

Displays Yes and No buttons

vbRetryCancel 5

Displays Retry and Cancel buttons


Table 9.2 Controlling the Icons

Named
Constant Value Description Icon

vbCritical> 16 Displays Critical Message icon icon*

vbQuestion> 32 Displays Warning Query icon Query icon*

vbExclamation> 48 Displays Warning Message icon Message icon*

vbInformation> 64 Displays Information Message icon icon*


Table 9.3 Controlling the Default Buttons

Named Constant

Value

Description

vbDefaultButton1 0

First button is default

vbDefaultButton2 256

Second button is default

vbDefaultButton3 512

Third button is default


Table 9.1 describes the layout of the buttons on the dialog box. When you decide it's time for a message box, consider the set of buttons the message box needs. Figure 9.2's message box didn't specify a intStyle value, so Visual Basic used the default value of 0 that sends only a single button--OK--to the message box. (The message box in Figure 9.2 contains only an OK button because it has 0 for intStyle.) If you want a style of buttons different from the single OK button, use a different value from Table 9.1.

If you want an icon to appear inside the dialog box, add one of the values from Table 9.2 to the intStyle value from Table 9.1. In other words, if you want the OK and Cancel buttons to display (an intStyle of 1) and you want the Warning Query icon to display (an intStyle of 32), you specify 33 for the intStyle (both table values added together).

A dialog box always contains a default button, which appears outlined to look as though someone is selecting it. (In other words, the button has the focus.) If users press Enter without selecting another button, the button defined as the default is selected. Therefore, if you want the Cancel button (the second button described in the preceding paragraph) to be the default button when the dialog box appears, add an additional 256 to the 33 to get a total of 289.


Message boxes respect the Windows Sound settings. Therefore, if users have set up a specific sound for one of the message box icons, such as the critical warning icon, the sound will appear along with the message box.

Example

Suppose that you want to display the dialog box shown in Figure 9.3. (Notice that the center button is the default.) Use the following MsgBox() function to create this dialog box:

i = MsgBox("Is the printer on?", 291, "Question Box")

Figure 9.3
Message boxes can become rather complex.

Reinforced Learning

Adding the intStyle values together can be cumbersome, but thanks to Visual Basic, you don't even have to add. Use an expression that adds the named constants shown in this topic's tables. The following MsgBox() function works just like the preceding example because the sum of the added intStyle values:

i = MsgBox("Is the printer on?", vbYesNoCancel + vbQuestion +

[ccc]vbDefaultButton2, "Question box")

Again, such statements are a bit cumbersome to type initially, but you'll appreciate the self-documenting code if you ever have to modify the message box.

Topic 2: Working with MsgBox()'s Return Values

The MsgBox() function is useful for displaying messages, but you'll want to know which buttons the users clicked when they close the dialog box. If the message box displayed only an OK button, your program knows that the users clicked only the OK button to close the message box. If, however, the message box contains additional buttons, your program should respond according to the button the users click.


Keep in mind that your application basically comes to a halt during the display of the message box. The MsgBox() function triggers the display of the message box, and no other line in the code can execute until users close the message box by clicking one of the message box buttons.

The message box function's return value indicates the button clicked by users. Therefore, after the function displays multiple buttons, your program can determine which button users chose by testing the return value.


You may have already guessed that the conditional operators you learned in Hour 8 helps test the message-box return values. In Hour 10, you'll learn how specifically to use the conditional operators to test for which button the users clicked.

Table 9.4 describes the return values that come from MsgBox().

Table 9.4 MsgBox() Return Values

Named Constant

Value

Description

vbOK 1

Users clicked OK

vbCancel 2

Users clicked Cancel

vbAbort 3

Users clicked Abort

vbRetry 4

Users clicked Retry

vbIgnore 5

Users clicked Ignore

vbYes 6

Users clicked Yes

vbNo 7

Users clicked No

Example

The following assignment statement does a lot:

intButton = MsgBox("Are you ready?", vbYesNoCancel + vbQuestion)

When Visual Basic reaches this statement, the program waits for users to answer the MsgBox() prompt by choosing one of the message box buttons. The result of the button choice, a numeric value from Table 9.4, is then assigned to the variable intButton.

vbYesNoCancel sends the Yes, No, and Cancel buttons to the dialog box, and vbQuestion displays the Warning Query icon. If the users choose Yes, the intButton variable is assigned the value 6. intButton gets a 7 if the users choose No and gets 2 if the users choose Cancel. Although your program will work with this return value, you'll want to use Table 9.4's named constants instead of the actual values.

FAST TRACK
How many buttons can users click for each message box your program displays? No matter how many buttons the message box displays, users can click at most one button in response to the message box. Users must press a button to get rid of the message box (or click Cancel or the message box's Close window button, which selects one of the buttons by default). Therefore, every MsgBox() function that your program issues will get only one button click in response to the message box. Not coincidentally, every function returns only one value. The value might be any one of the data types, depending on the function's goals. When you get to Hour 13's lesson, you'll learn more about the single return value that all functions return.

Reinforced Learning

Don't confuse the return value with the button you select. For example, the return value might be 3, meaning that the users clicked the Abort button and you may have used 3 (better indicated by the vbYesNoCancel named constant) to describe the buttons that you want displayed. Therefore, when the message box appears with the buttons you've selected, the return value might overlap one of your message box values but the number's meaning is now totally different. After the program gains control from the message box function, you test against Table 9.4's values to determine what users did.

If users press Esc at any dialog box that contains a Cancel button, Visual Basic acts as though they chose the Cancel button and returns the value 2 from the MsgBox() function. In Hour 10, you learn how to test the return value of MsgBox() and execute code depending on which button the users choose.

Topic 3: The InputBox() Function

The InputBox() function gets data from users by displaying an input box. Of course, the MsgBox() function also gets data from users, but the data is only the button number that the users clicked. The InputBox() function is the opposite of the MsgBox() function; whereas MsgBox()'s primary purpose is to display data for users, the InputBox() function's purpose is to receive user input.

Overview

You're well aware of the ease with which forms allow users to enter data. When you begin to create powerful Visual Basic applications, however, you must have a way to ask users questions interactively so that your programs can act on their responses. Input boxes do just that.

Figure 9.4 shows an example input box. As you can see, an input box contains a title bar, a prompt, command buttons, and a text box area to receive user input.

Figure 9.4
The input box asks users for information.


Visual Basic no longer supports the special function named InputBox$(). Previous versions of Visual Basic supported this string-related function.

The InputBox() Format

Here is the format of the input box function:

strAnswer = InputBox(strPrompt[, strTitle][, strDefault][, intXpos][, intYpos])

When users answer the input box and close it, the variable indicated at strAnswer, a string variable, will hold the users' answer.

strPrompt is a string that you want displayed so that users know what you're asking for. Always ask users a question or describe the input you want; otherwise, users will have no way of knowing what to enter in response to the input box. The strPrompt value can be as long as 1,024 characters.

The optional strTitle string value becomes the input box's title. Visual Basic displays the application's name for the title if you don't specify one yourself.

The optional strDefault value is a default string that appears inside the typing area. Figure 9.4 showed no default string, but if the input box asks for a predictable response, you can speed the users' operation by displaying a default response that users can accept or change. Users accept the default string by pressing Enter if they don't want to enter a new value.


If you leave out strTitle or strDefault (or both), their commas are still required in the code as placeholders.

The optional intXpos and intYpos variables indicate the numeric value of the twips where you want the input box to appear on-screen. If you've displayed a message, table, or form somewhere on-screen, you can position the input box wherever you want it to appear (as opposed to the middle of the screen, if you specified no position). intXpos is the x coordinate (the horizontal position), and intYpos is the y coordinate (the vertical position).


A twip is 1/1440 of an inch and 1/567 of a centimeter (very small indeed).

Example

Figure 9.5 shows an input box generated from the following InputBox() function (assume that strUserName is declared to be a String variable):

strUserName = InputBox("What is your name?", "Ask a name", "John Doe")

Figure 9.5

Input boxes wait for the user's response.

The InputBox() functions always offer a typing area for users to enter a value and an OK button so that users can indicate when the input is completed. After users enter a name (or press Enter to choose OK and use the default John Doe), the variable strUserName holds the users' answer.

Reinforced Learning

Unlike message boxes, you can't control which command buttons appear inside input boxes. Remember that the goal for input boxes is to get an answer of some kind. If you just need to know the answer to a yes or no question, use a message box and get users to click the Yes or No command button. If you need more of a response, however, use the InputBox() function so that users can enter a response into a string variable or control.

If you want Visual Basic to display the input box in the center of the screen, omit the intXpos and intYpos values. If you want the input box to appear at a particular location on-screen, you can specify the exact placement by specifying the x- and y-coordinates like this:

strUserName = InputBox("What is your name?", "Ask a name", "John Doe", 100, 50)

If you want to use the screen's physical coordinates based on the Screen object's Left and Top properties, you can embed expressions for the two placement values.


You learned about the Screen object in Hour 4's lesson, "Activating Controls."

Summary

You can now display professional-looking dialog boxes from within Visual Basic. If you ever want to give users a little extra message or get their attention in a way that a regular form control can't do, display a dialog box with MsgBox(), a built-in function. If you need to test to see which buttons the users choose, you can call the MsgBox() function and test the return value.

You also learned how to write programs that accept input from the keyboard. Before this hour's lesson, you had to assign variables values at the time you wrote the code. You can now write programs that prompt for variable data, and users then enter data when the procedure runs.

Often you see MsgBox() and InputBox() functions next to each other in code. The MsgBox() function displays information, and the InputBox() might ask the users questions about that information.

Now that you can get user responses to your questions, Hour 10's lesson explains how to act on that response. Being able to control a program's execution based on data is vital for true data processing. Your program must be able to respond and make decisions based on values in tables and variables. Hour 10's lesson introduces you to conditional programming, a fancy term for writing programming statements that use the conditional operators to test data values and act according to the results of the test.


Hour 9 Quiz

  1. What's the difference between a message box and an input box?
  2. Which of the following can you not do with a message box?
    1. Display output for users
    2. Test to see which message box button the users clicked
    3. Receive an answer string
    4. Display warnings to users
  3. True or false: A sound can accompany a message box.
  4. Which function do you use to get an answer from the user--MsgBox() or InputBox()?
  5. True or false: Tables 9.1, 9.2, and 9.3 provide the values for three different MsgBox() values.
  6. What is a twip?
  7. Why does the InputBox() function let you display output (strPrompt) when the function is an input-only function?
  8. If you don't specify your own title string, what happens when Visual Basic executes a MsgBox() function?
  9. If you don't specify your own title, what happens when Visual Basic executes an InputBox() function?
  10. Where does the InputBox() input box appear on-screen if you don't specify placement coordinate values?

Homework 9 Exercises

  1. Write a MsgBox statement that displays your name and an OK button.
  2. Write a procedure that asks users for their first names, and then asks for their last names. After users enter the two names, concatenate the names together, store them in a string variable, and display the full name (with an appropriate separator space) in a message box.
  3. Write the MsgBox() needed to generate the message box shown in Figure 9.6.

    Figure 9.6

    How was this dialog box generated?


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