How Can I Prompt a User for Input?
Hey, Scripting Guy! I need my script to prompt users to enter some information, like the name of the file they want to create. How do I do that?
— RW, Williamsport, PA
Hey, BN. The simplest – and most foolproof – way to do this is to use an InputBox; when you do that users will be presented with a graphical dialog box similar to this:
Displaying the dialog box is easy; you simply call the InputBox function, passing that function two parameters:
The message to be displayed.
In this example, the message is Please enter a name for your new file:.
The caption for the dialog box.
In this example, the caption is Create File.
The code itself looks something like this:
strAnswer = InputBox(“Please enter a name for your new file:”, _ “Create File”)
Note that the variable strAnswer will be used to store whatever the user types into the dialog box.
So far so good. Now, how do you figure out what file name the user typed in? That’s easy; like we said, the value the user enters is automatically stored in the variable strAnswer. Thus:
strAnswer = InputBox(“Please enter a name for your new file:”, _ “Create File”) Wscript.Echo strAnswer
There’s only one complication here. As you can see, the dialog box has both an OK button and a Cancel button. The idea is that the user types in a file name and then clicks OK. But what happens if the user clicks Cancel? Theoretically, that means that the user doesn’t want to create a file after all; because of that, the script should either terminate or move on to some other task.
Fortunately, this a case where theory can easily be put into practice. Any time a user clicks the Cancel button, strAnswer is set to an empty string (e.g., strAnswer = “”). To determine whether the user clicked Cancel (or, alternatively, clicked OK without entering a file name), all we have to do is check to see if strAnswer equals an empty string. This modified script checks the value of strAnswer; if strAnswer is empty the script terminates (using Wscript.Quit). Otherwise, the script echoes the value the user typed into the dialog box:
strAnswer = InputBox(“Please enter a name for your new file:”, _ “Create File”) If strAnswer = “” Then Wscript.Quit Else Wscript.Echo strAnswer End If
Here’s a variation which places the InputBox in a loop. If the user clicks Cancel, the script reminds the user to enter a file name, and then displays the InputBox again. As soon as the user enters a file name and clicks OK, the script displays the value entered and then exits the loop (Exit Do):
Do While X = 0 strAnswer = InputBox _ (“Please enter a name for your new file:”,”Create File”) If strAnswer = “” Then Wscript.Echo “You must enter a file name.” Else Wscript.Echo strAnswer Exit Do End If Loop
For more information about the Input function, see the VBScript documentation on MSDN.