How Can I Give a User a Yes/No Prompt?


Hey, Scripting Guy! Question

Hey, Scripting Guy! I have a script which performs some file management tasks, and then should ask the user whether or not they want to delete a set of files. How do I ask a user a Yes or No question like this?

— SE, Casper, WY

SpacerHey, Scripting Guy! AnswerScript Center

Hey, SE. There are a couple different ways that you can do this, but because you’re dealing with users the best way is probably to just pop up a message box and let them click Yes or No. How hard is that? Hey, it’s no harder than these few lines of code:

intAnswer = _
    Msgbox("Do you want to delete these files?", _
        vbYesNo, "Delete Files")
If intAnswer = vbYes Then
    Msgbox "You answered yes."
    Msgbox "You answered no."
End If

All we’re doing here is creating a message box that features the following:

The message to be displayed.

In this example, the message is Do you want to delete these files?

A Yes button and a No button.

This is specified by the VBScript constant vbYesNo. There are other values that can give you different message box configurations; for example, you could have a message box with buttons labeled Abort, Retry, and Ignore. Who could forget good old Abort, Retry, and Ignore?

The message box caption.

In this example, the caption is simply Delete Files.

The message box will sit there until the user clicks a button. And how do we know which button was clicked? Well, the results of the button click are stored in the variable intAnswer. All we have to do is check the value of intAnswer. If intAnswer is equal to another VBScript constant (vbYes) then we know the user must have clicked yes; if it’s equal to anything else, then they must have clicked No. (After all, we only have two buttons, so if they didn’t click Yes they had to have clicked No.)

For more information about the MsgBox function, see the VBScript documentation on MSDN.


Comments are closed.