[Previous] [Table of Contents] [Next]

# Using the MsgBox Function in VBScript

The Echo method offers a simple way to create dialog boxes in a script. You simply call the method and pass all values to be displayed as parameters. But Echo doesn't provide any options for influencing the layout of the dialog box. You might want to define particular text for the dialog box's title bar, for example, or you might want to insert buttons in addition to the OK button.

If you've worked with Microsoft Visual Basic or Visual Basic for Applications (VBA), you're probably familiar with the MsgBox function, which provides an easy way to show a message in a dialog box. (JScript doesn't support the MsgBox function.) This function also allows you to define the title text, the icon that appears in the dialog box, the number of buttons, and so on. Fortunately, the MsgBox function is implemented in VBScript, so you can use all its features in a VBScript program.

> NOTE

> You can use MsgBox as a procedure to display some results, or you can call MsgBox as a function to retrieve some values from the dialog box. I'll go into more detail shortly.

If you don't care about the value returned by the MsgBox function, you can call it using the following syntax:

    MsgBox prompt, buttons, title

The parameters in this call are as follows:

- prompt A required parameter that defines the text that appears in the dialog box itself. You can insert the VBScript constant vbCrLf into the output string to force a new line in the text.

- buttons An optional parameter that defines the buttons and the icon shown in the dialog box. If you omit this parameter, VBScript uses only the OK button in the dialog box.

- title An optional parameter that defines the text of the dialog box's title bar. If you omit this parameter, Windows shows the application name in the title bar.

> NOTE

> MsgBox supports two additional optional parameters, helpfile and context, which allow you to include a Help button in the dialog box. Because creating help files is beyond the scope of this book, I don't explain how to use these parameters. (I don't think it makes much sense to use them without having a customized help file.)

As you can see, you can omit some parameters, but you must pass a value for the prompt parameter. Let's look at what happens if you omit optional parameters. Listing 6-3 is a minimal VBScript program. (MsgBox.vbs is in the \WSHDevGuide\Chapter06 folder on the companion CD.)

Listing 6-3 MsgBox.vbs

    '************************************************
    ' File:    MsgBox.vbs (WSH sample in VBScript)
    ' Author:  (c) G. Born
    '
    ' Using the MsgBox procedure to show a message
    '************************************************
    Option Explicit

    ' Use all parameters in this call.
    MsgBox "This is step 1", 0, "WSH sample by G. Born"

    ' Now omit the second parameter.
    MsgBox "This is step 2", , "WSH sample by G. Born"

    ' Now omit the third parameter.
    MsgBox "This is step 3", 0

    '*** End

The program in Listing 6-3 creates three dialog boxes. The first MsgBox call, shown here, defines all parameters in the statement:

    MsgBox "This is step 1", 0, "WSH sample by G. Born"

This statement creates a simple dialog box (the first dialog box in Figure 6-5). The first parameter, "This is step 1", is the message shown in the dialog box. The second parameter is set to 0, so the only button is the OK button. The last parameter contains the string "WSH sample by G. Born", which appears as the title bar text.

Figure 6-5 Dialog boxes created with MsgBox

In the second MsgBox call, the value of the buttons parameter is omitted by using two commas as follows:

    MsgBox "This is step 2", , "WSH sample by G. Born"

This call creates the second dialog box shown in Figure 6-5. It is identical to the first dialog box (except for the message text) because omitting the buttons parameter is the same as setting the value to 0 (the default).

If you omit the third parameter, the one for the title text, you get the third dialog box in Figure 6-5.

    MsgBox "This is step 3", 0

The title bar contains only the application's name. In WSH 2, the VBScript language engine shows the text VBScript.

> NOTE

> Omitting the second and third parameters in a MsgBox call is similar to using an Echo method call, which creates a dialog box with an OK button and the text passed in the first parameter. Only the title text parameter distinguishes Echo and MsgBox. Echo creates the Windows Script Host title bar text because this method is exposed from WSH. MsgBox creates the VBScript title text, which indicates that the language engine provides the procedure.

## Defining the Icon and Buttons in a Dialog Box

You can use the second parameter of the MsgBox call to define the icon, the number of buttons, and their captions in the dialog box. The values for this parameter are predefined in Windows; VBScript provides named constants for their values. Table 6-1 describes the MsgBox constants for the icons.

Table 6-1 MsgBox Constants for Icons

Constant* | Icon | Description
--- | --- | ---
0 | none | No icon (default)
16 or vbCritical |  | Stop
32 or vbQuestion |  | Question mark
48 or vbExclamation |  | Exclamation point
64 or vbInformation |  | Information

* This first column contains numeric as well as named VBScript constants. You can use either one, but named constants are much more readable.

The buttons parameter can also contain additional constants to define the buttons in the dialog box. Table 6-2 lists the predefined constants used for this purpose. To show an icon and a button combination in the dialog box, you simply add the constants shown in Table 6-1 and Table 6-2.

Table 6-2 MsgBox Constants for Buttons

Constant | Description
--- | ---
0 or vbOKOnly | OK button (default)
1 or vbOKCancel | OK and Cancel buttons
2 or vbAbortRetryIgnore | Abort, Retry, and Ignore buttons
3 or vbYesNoCancel | Yes, No, and Cancel buttons
4 or vbYesNo | Yes and No buttons
5 or vbRetryCancel | Retry and Cancel buttons

To show a dialog box containing a question mark icon and the OK button, you can write this statement:

    MsgBox "Question", _
           vbOKOnly + vbQuestion, _
           "MsgBox demo"

You can see how useful named constants are. Using vbOKOnly + vbQuestion clearly indicates what you want; the equivalent constant 32 is a bit cryptic.

### Example: Showing different buttons

Listing 6-4 creates a dialog box for each of the six available button combinations. (Figure 6-6 shows a three-button dialog box only.)

Figure 6-6 A dialog box with three buttons created using MsgBox

Listing 6-4 MsgBox1.vbs

    '************************************************
    ' File:    MsgBox1.vbs (WSH sample in VBScript)
    ' Author:  (c) G. Born
    '
    ' Showing buttons in a dialog box
    '************************************************
    Option Explicit

    Dim text

    text = "WSH sample by G. Born"

    ' Use three parameters in each call.
    MsgBox "vbOKOnly " & vbOKOnly, vbOKOnly, text

    MsgBox "vbOKCancel " & vbOKCancel, vbOKCancel, text

    MsgBox "vbAbortRetryIgnore " & vbAbortRetryIgnore, _
            vbAbortRetryIgnore, text

    MsgBox "vbYesNoCancel " & vbYesNoCancel, vbYesNoCancel, text

    MsgBox "vbYesNo " & vbYesNo, vbYesNo, text

    MsgBox "vbRetryCancel " & vbRetryCancel, vbRetryCancel, text

    '*** End

> NOTE

> The captions that appear on the buttons depend on the localized Windows version. Table 6-2 lists the button captions for the U.S. Windows version.

## Setting the Focus on a Button

One button in the dialog box receives the focus for closing the dialog box. By default, the leftmost button gets the focus. If the user presses the Enter key, the button with the focus is used to close the dialog box.

You can set the focus on a button other than the default button. For example, in a dialog box that includes OK and Cancel buttons and that asks whether the user wants to delete a file, you probably want to set the focus on the Cancel button so that the user won't inadvertently delete the file by pressing Enter.

You set the focus by using a value passed in the buttons parameter. Table 6-3 lists the constants you can use to set the button that gets the focus. You must add the constant to the values for the icon and the button.

Table 6-3 MsgBox Constants for Setting the Button Focus

Constant* | Descriptions
--- | ---
0 or vbDefaultButton1 | Sets the focus to the first button (default)
256 or vbDefaultButton2 | Sets the focus to the second button
512 or vbDefaultButton3 | Sets the focus to the third button

* The value 768 (vbDefaultButton4) sets the focus to the fourth button. Because ordinary dialog boxes don't have four help buttons, I haven't added an entry to the table.

> TIP

> MsgBox also supports the constant vbSystemModal (value 4096). Adding this constant to the buttons parameter (as in MsgBox "Hello", vbOKOnly + vbSystemModal, "Foreground") forces Windows always to show the dialog box window in the foreground.

## Determining Which Button Was Used to Close a Dialog Box

Sometimes you need to know which button the user clicked to close a dialog box. In the dialog box on the left in Figure 6-7, the user can click either OK or Cancel to close the dialog box. The dialog box on the right indicates which button was used.

In VBScript, you can use the return value of the MsgBox function to determine which button was clicked to close the dialog box. To retrieve its return value, you call the MsgBox function using the following syntax:

    result = MsgBox(prompt, buttons, title)

Figure 6-7 A dialog box with two buttons and a dialog box showing which button was clicked

You can create the dialog box on the left in Figure 6-7 using the following statement:

    result = MsgBox("Please click a button", _
                    vbQuestion + vbOKCancel, _
                    "WSH MsgBox sample by G. Born")

You can assign the MsgBox return value to a variable and then test the value to determine which button was used to close the dialog box. Table 6-4 lists valid return values from the MsgBox function. The values returned depend on which buttons are in the dialog box.

Table 6-4 MsgBox Return Codes

Constant | Button Clicked
--- | ---
1 or vbOK | OK
2 or vbCancel | Cancel
3 or vbAbort | Abort
4 or vbRetry | Retry
5 or vbIgnore | Ignore
6 or vbYes | Yes
7 or vbNo | No

You can use either the numeric or the symbolic constant. Being able to check which button is clicked enables you to write code that allows the user to choose between options at run time.

The VBScript sample shown in Listing 6-5 checks which button was used to close the second dialog box. The result, with the button's name, is shown in a third dialog box.

Listing 6-5 MsgBox2.vbs

    '************************************************
    ' File:    MsgBox2.vbs (WSH sample in VBScript)
    ' Author:  (c) G. Born
    '
    ' Checking the value returned by MsgBox
    '************************************************
    Option Explicit

    Dim Text1, Text2, Text3, Text4
    Dim Title, result

    ' Define texts.
    Title = "WSH MsgBox sample by G. Born"
    Text1 = "Just a note: Windows Script Host"
    Text2 = "OK button clicked"
    Text3 = "Cancel button clicked"
    Text4 = "Please click a button"

    ' Call the MsgBox function.
    ' MsgBox prompt, buttons, and title
    ' prompt:    the text shown in the dialog box
    ' title:     the dialog box title
    ' buttons:   the buttons
    MsgBox Text1, vbInformation + vbOKOnly, Title

    ' Check which button was clicked.
    ' result = MsgBox(prompt, buttons, title)
    result = MsgBox(Text4, vbQuestion + vbOKCancel, Title)

    ' Inspect the return value.
    If result = vbOK Then
        WScript.Echo Text2    ' Show result using the Echo method.
    Else
        WScript.Echo Text3
    End If

    '*** End

The variables Text1, Text2, and so on define the messages shown in the dialog boxes. During execution, the script shows three dialog boxes. The first dialog box has only an OK button, and the second one has two buttons that close the dialog box. Listing 6-5 uses the following statements to check the MsgBox return code:

    ' Inspect the return value.
    If result = vbOK Then
        WScript.Echo Text2    ' Show result using the Echo method.
    Else
        WScript.Echo Text3
    End If

After the user closes the dialog box, the program checks the return value to see whether OK or Cancel was used. If the return value is vbOK, the If block is executed and the result is shown in a third dialog box (which is created using the Echo method).

    WScript.Echo Text2

In this statement, WScript.Echo shows the content of the variable Text2 in the dialog box. If the return value is vbCancel, however, the Else block is executed and Text3 is displayed in the dialog box.

## Example: A Welcome Login Message in VBScript

Let's look at another example that uses MsgBox. An administrator can define a custom welcome message for a machine running Microsoft Windows 95, Windows 98, Windows NT, or Windows 2000. By default, the user sees a static welcome message after logging in. We'll define a custom version of that dialog box that has a different message for each day of the week. Figure 6-8 shows the messages for Sunday and Monday.

Figure 6-8 Welcome dialog boxes for Sunday and Monday

You can implement this custom dialog box by using just a few script statements. Let's go over each step. You display a dialog box with a title bar using a MsgBox procedure call. If you don't know how to get the user's name, you can define a name as a constant:

    Const title = "Hello, Jim!"    ' The user name

Then you define two variables, text and cNotes:

    Dim text
    Dim cNotes

The variable text collects the current date. The variable cNotes stores the messages for each day. Unfortunately, a simple variable can contain only one value (a text string, for example). To show a different message for each day of the week, you need several distinct strings, which can't be assigned to a simple variable.

Instead, you must use an array to hold the strings. An array is a variable that can contain several distinct values. In VBScript, you can define an array as follows:

    Dim cNotes(10)

The array cNotes consists of 11 elements: cNotes(0), cNotes(1), and so on through cNotes(10). You can assign a value to each array element by using the following code:

    cNotes(0) = "Hey, it's Sunday. Please take a rest, my friend."
    cNotes(1) = "It's Monday. Let's begin the week."
    MsgBox cNotes(0) & vbCrLf & cNotes(1)

With this approach, you have to write down a lot of assignment statements to fill the array with its content. Because you need seven strings, one for each day of the week, it's better to use the VBScript Array function. The Array function lets you define all array items within one statement:

    cNumber = Array(1, 2, 3, 4)

This statement assigns the numbers 1, 2, 3, and 4 to the array elements cNumber(0), cNumber(1), cNumber(2), and cNumber(3). You can thus use the following statement to fill a string array:

    cNotes = Array( _
                "Hey, it's Sunday. Please take a rest, my friend.", _
                "It's Monday. Let's begin the week.", _
                "Oops, it's Tuesday. One day of the week is gone.", _
                "Don't worry, it's Wednesday.", _
                "Hurray, it's Thursday.", _
                "Thank goodness it's Friday.", _
                "Saturday! Why don't you relax this weekend?")

The variable cNotes is used as an array that contains messages for each day of the week. The following statement shows the message for Sunday:

    MsgBox cNotes(0)

Now you need to determine the current day, derive the day of the week, and use the weekday value as an index into the cNotes array to retrieve the correct greeting. The VBScript function Weekday returns the weekday code of a given date. The code Weekday(Now()) returns a value of 1 for Sunday, 2 for Monday, 3 for Tuesday, and so on. Note that the string for Sunday must be recalled using cNotes(0). Thus, the statement cNotes(Weekday(Now()) - 1) retrieves the day's message stored in the cNotes array.

The dialog boxes shown earlier in Figure 6-8 also contain the current date, which you get using the Now function. Because this function delivers the date in a predefined format, you can use other VBScript functions to extract the day, the month, and the year from the current date:

    text = WeekDayName(Weekday(Now()), False, 1) & _
            ", " & MonthName(Month(Now)) & " " & _
            Day(Now()) & ", " & _
            Year(Now())

You obtain the name of the day of the week using the WeekDayName function. The first parameter passed to this function is the code for the day of the week. The second parameter defines whether the return value is abbreviated. A value of False forces the function to return the full day-of-the-week name. The last parameter is optional and defines the code for the first day of the week. WeekDayName(Weekday(Now()), False, 1) returns a string such as Sunday or Monday.

MonthName(Month(Now)) works in a similar way. The VBScript function Month gets the current date from the function Now (which is passed as a parameter). Month extracts the month value from the date passed as a parameter, and MonthName returns the name of the month. By using these VBScript functions, you can format the date as needed. You can omit the year or the month, and you can sort the date based on your local time zone.

The full sample is shown in Listing 6-6. (For details about all the VBScript functions, see the VBScript Language Reference, which is available on the book's CD.)

Listing 6-6 Welcome.vbs

    '************************************************
    ' File:    Welcome.vbs (WSH sample in VBScript)
    ' Author:  (c) G. Born
    '
    ' Using MsgBox to show a welcome message that
    ' changes daily
    '************************************************
    Option Explicit

    ' Define constant and variables.
    Const title = "Hello, Jim!"    ' The user's name
    Dim text
    Dim cNotes

    ' Now we define an array with the daily messages.
    cNotes = Array ( _
                "Hey, it's Sunday. Please take a rest, my friend.", _
                "It's Monday. Let's begin the week.", _
                "Oops, it's Tuesday. One day of the week is gone.", _
                "Don't worry, it's Wednesday.", _
                "Hurray, it's Thursday.", _
                "Thank goodness it's Friday.", _
                "Saturday! Why don't you relax this weekend?")

    ' Here we define the date within the welcome message.
    text = WeekDayName(Weekday(Now()), False, 1) & _
            ", " & MonthName(Month(Now)) & " " & _
            Day(Now()) & ", " & _
            Year(Now())

    ' Now we append a custom message to the date.
    text = text & vbCrLf & vbCrLf & cNotes(Weekday(Now()) - 1)

    ' Display the message.
    MsgBox Text, vbOKOnly + vbInformation, title

    '*** End

> NOTE

> To display the welcome messages in Listing 6-6, copy the sample file Welcome.vbs to a local folder on your hard disk. Drag the file's icon to the Start button, to Programs, and then to Startup. Each time Windows starts, the content of the Startup folder is executed and the welcome message will appear.