- Introduction to VBScript
- Flow Control
- VBScript Functions
- Interacting with the User
- Advanced VBScript Topics
- Where to Go from Here
Interacting with the User
VBScript is not designed for writing programs with complex user interfaces, but it can display simple messages and receive simple input strings from the user with its MsgBox and InputBox functions.
The MsgBox() Function
In its most basic form, MsgBox displays a text message to the user. For example, the following code produces the output shown in Figure 2.2:
' example file script0210.vbs MsgBox "This message was displayed by VBScript at " & time()
Figure 2.2 A basic message box displaying a string to the script user.
You can also use MsgBox to ask simple yes/no questions of the script's user. To do so, you use the advanced form of the MsgBox function, with the following syntax:
MsgBox(prompt [, buttons] [, title])
The three arguments are as follows:
- prompt specifies the text to display.
- buttons specifies which buttons to offer to the user.
- title is a text title displayed at the top of the resulting dialog box.
You can omit the buttons and title arguments; in their absence, VBScript displays just an OK button and the title "VBScript." The values for buttons needs to be one of those listed in Table 2.6. You can use the constant name or the numeric value.
Table 2.6. Buttons Options for the MsgBox() Function
Constant Name |
Value |
Displays |
VbOKOnly |
0 |
The OK button |
VbOKCancel |
1 |
The OK and Cancel buttons |
VbAbortRetryIgnore |
2 |
The Abort, Retry, and Ignore buttons |
VbYesNoCancel |
3 |
The Yes, No, and Cancel buttons |
VbYesNo |
4 |
The Yes and No buttons |
VbRetryCancel |
5 |
The Retry and Cancel buttons |
For example, you can tell the user that a required file wasn't found and ask whether to proceed by using this code:
choice = MsgBox("The preferences file is missing, should I proceed?", vbYesNo)
MsgBox returns either the value vbYes or vbNo, depending on the button clicked. The possible return values for MsgBox are listed in Table 2.7. The value indicates which of the buttons the user has selected.
Table 2.7. Return Values from the MsgBox() Function
Constant Name |
Value |
VbOK |
1 |
VbCancel |
2 |
VbAbort |
3 |
vbRetry |
4 |
vbIgnore |
5 |
VbYes |
6 |
VbNo |
7 |
You can ask VBScript to display an icon along with the message by adding an additional value to the buttons argument, using one of the values listed in Table 2.8.
Table 2.8. Icon Values to Use with the MsgBox() Function
Constant Name |
Value |
Displays |
VBCritical |
16 |
Critical Message icon |
VBQuestion |
32 |
Question icon |
VbExclamation |
48 |
Exclamation icon |
VBInformation |
64 |
Information icon |
The following code displays a message with an Information icon:
' example file script0211.vbs x = 33 MsgBox "The value of variable x is " & x, vbOKOnly + vbInformation,_ "Debugging Info"
The results are shown in Figure 2.3. The vbInformation option also causes Windows to play a special Information sound, which, alas, you'll have to run the sample script yourself to hear.
Figure 2.3 A MsgBox with a title and an icon.
Sometimes you'll want MsgBox to display some interesting message but won't care which button the user clicks. In this case, omit the parentheses from the MsgBox call. I discussed this point earlier in the chapter in the section "Calling Functions and Subroutines."
The MsgBox function displays a dialog box that stays up until the user clicks a button. Don't use it in a script that needs to run unattended! Your script will never finish because it will be waiting for a user who isn't watching.
If you want to display information without stopping the script, you can use the Wscript.Echo statement, as I'll discuss in the next section.
The InputBox() Function
VBScript lets you ask your users for a simple text string by using the InputBox function, as in this example:
' example file script0212.vbs UserName = InputBox("Please enter your first name") MsgBox "Hello, " & UserName
This script displays the input-type dialog box shown in Figure 2.4.
Figure 2.4 The InputBox() function as seen by the user.
The function returns whatever the user types. In the preceding example, this is stored in the variable UserName.
As with MsgBox, you can add additional arguments to the InputBox function to get better control of its appearance. You can use several options, only three of which are really interesting:
InputBox(prompt, title, default)
Here, prompt is the message to display above the input field, title is the title to display at the top of the dialog box, and default places a specific character string into the editing field when it first appears; the user can then accept or change this value.
A practical use of InputBox is to select a folder for the script to process, as in this example:
fldr = InputBox("Enter folder to be cleaned up", "Cleanup Script", "C:\TEMP")
Because VBScript is so flexible about the types of data stored in its variables, if your user types 23, the value returned by InputBox can be treated as a number or as a string. Here's a handy script to calculate square roots (something I'm sure you need to do several times a day):
do num = InputBox("Enter a number", "Square Root Calculator", "0") if num < 0 then MsgBox "You can't take the square root of a negative number like " &_ num, VbOKOnly+VbExclamation elseif num = 0 then exit do ' entering 0 ends the program else MsgBox "The square root of " & num & " is " & sqr(num), VbOKOnly end if loop
This script will fail with an error message if the user types something nonnumeric, such as "XYZ." It's always best to check a user's input for correctness so that the program will either tell the user when something is wrong or at least behave sensibly if it is. Here's how:
InputBox displays a Cancel button. If the user clicks the Cancel button instead of OK, InputBox returns the empty string (""). You can detect this with a statement such as the following:
str = InputBox("Please enter your name:") if len(str) = 0 then ...
Then you can respond appropriately by exiting the script, ending a loop, and so on. In the square root calculator, it turns out that the empty string satisfies the IsNumeric test and evaluates as 0, so the calculator responds correctly to Cancel without this test.
Printing Simple Text Messages with Wscript.Echo
When you're debugging a particularly obstinate script, at some point you'll probably want to see what's held in your script's variables while the program runs. However, if you need to print debugging output inside a loop, or if you have dozens of variables to display, and you try to use MsgBox for this job, you'll quickly get tired of clicking OK over and over. There's a better way: The Wscript.Echo command can display text without stopping your program.
The Wscript.Echo command is useful in scripts even when you're not debugging—sometimes you'd like a script to display text information on your screen. Later in the book, I'll show you scripts that display lists of folder contents, user accounts, network shares, and other information in Chapters 4 and beyond.
The command is simple:
wscript.echo expression
This prints the value of any expression, of any type: Date, Numeric, Text, or Boolean. You can list any number of expressions, separated by commas, as in
wscript.echo expression, expression , expression
and VBScript will display each of them, separated by a single blank space.
For example, the script
username="Mary Smith" lastlogondate=#03/04/2002# wscript.echo username & "'s last logon was", lastlogondate
will display the text
Mary Smith's last logon was 3/4/2002
Note that I added "'s" to the username string using the string concatenation operator &. (I'm picky about this sort of thing. I like computer output to use proper English.)
As you saw earlier, VBScript is very flexible joining strings with & and will actually let you join any variable type with a string—it will convert a Boolean, Date, or Numeric variable or expression to a string and then join the resulting strings. You can use this to add a period to the date at the end of the sentence, like so:
username="Mary Smith" lastlogondate=#03/04/2002# wscript.echo username & "'s last logon was", lastlogondate & "."
This prints, properly punctuated, as follows:
Mary Smith's last logon was 3/4/2002.
A Touchy Subject
Because I've taken a bit of a diversion into the topic of formatting messages, I'll add one more thing. How often do you see a computer print a sloppy message like this?
1 files deleted.
This drives me crazy. There's no reason for it, because it's simple to format this type of message correctly.
As an exercise, I'll leave it to you, the reader, to modify the sample script script0206.vbs so that it prints "1 bottle" rather than "1 bottles" at the end of the song.
You don't have to go to this trouble for a one-time, quick-and-dirty program, but if your program is going to be used by others, it's worth paying attention to language in this way.