Ask the User a Question

If you want your VBA code to ask the user a question and then perform some action based on the user's answer, use the more complex MsgBox function syntax and an If...Else...End If block of code with the general syntax, as shown here:

Dim variableName As Integer variableName = MsgBox("prompt",buttons,"title") If variableName = vbYes Then

'Code to execute if user clicked Yes goes here. Else

'Code to execute if user clicked No goes here. End If where

1 variableName is a name of your own choosing (such as Answer).

1 prompt is the text of the question that the box displays.

1 buttons is any VBA constant or sum of constants. (For a question like the one shown in Figure 16-2, use vbYesNo+vbQuestion.)

1 title is the title of message box.

1 'Code to execute if... represents any number of VBA statements.

Figure 16-2:

A question on the screen with Yes and No buttons.

Figure 16-2:

A question on the screen with Yes and No buttons.

In the following example, the statement

Answer = MsgBox("Did labels print OK?", vbYesNo+vbQuestion, "Question")

displays the message box shown in Figure 16-2. The question mark icon and Yes/No buttons are in the box courtesy of the vbQuestion+vbYesNo expression in the buttons argument:

Dim Answer As Integer

Answer = MsgBox("Did labels print OK?", vbQuestion+ vbYesNo, "Question")

If Answer = vbYes Then

MsgBox "You clicked Yes"

Else

MsgBox "You clicked No"

End If

In the preceding code example, when a user clicks a button, he just sees a little message specifying which button he clicked, which serves no practical purpose. In real life, replace MsgBox "You clicked Yes" and MsgBox "You clicked No" with code that does something useful.

Was this article helpful?

0 0

Post a comment