Chapter 15: Simple Dialog Boxes
Displaying a simple message box You can use the MsgBox function by itself or assign its result (that is, the button clicked by the user) to a variable. If you use this function by itself, don’t include parentheses around the arguments. The following example simply displays a message and does not return a result: Sub MsgBoxDemo() MsgBox “Click OK to begin printing.” End Sub Figure 15-1 shows how this message box looks.
Figure 15-1: A simple message box.
Getting a response from a message box If you display a message box that has more than just an OK button, you’ll probably want to know which button the user clicks. Fortunately, the MsgBox function returns a value that represents which button is clicked. You can assign the result of the MsgBox function to a variable. In the following code, I use some built-in constants (which I describe later in Table 15-2) that make it easy to work with the values returned by MsgBox: Sub GetAnswer() Dim Ans As Integer Ans = MsgBox(“Continue?”, vbYesNo) Select Case Ans Case vbYes ‘ ...[code if Ans is Yes]... Case vbNo ‘ ...[code if Ans is No]... End Select End Sub When you execute this procedure, the Ans variable is assigned a value of either vbYes or vbNo, depending on which button the user clicks. The Select Case statement uses the Ans value to determine which action the routine should perform.
225