18.11.2014 Views

Microsoft Office

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Creating UserForms 41<br />

The following example uses a combination of constants to display a message box with a Yes button, a No<br />

button (vbYesNo), and a question mark icon (vbQuestion); the second button is designated as the<br />

default button (vbDefaultButton2) — which is the button that is executed if the user presses Enter. For<br />

simplicity, these constants are assigned to the Config variable, and Config is then used as the second<br />

argument in the MsgBox function.<br />

Sub GetAnswer()<br />

Config = vbYesNo + vbQuestion + vbDefaultButton2<br />

Ans = MsgBox(“Process the monthly report?”, Config)<br />

If Ans = vbYes Then RunReport<br />

If Ans = vbNo Then Exit Sub<br />

End Sub<br />

Figure 41.4 shows how this message box appears when the GetAnswer Sub is executed. If the user clicks<br />

the Yes button (or presses Enter), the routine executes the procedure named RunReport (which is not<br />

shown). If the user clicks the No button, the procedure is ended with no action. Because the title argument<br />

was omitted in the MsgBox function, Excel uses the default title (“<strong>Microsoft</strong> Excel”).<br />

FIGURE 41.4<br />

The second argument of the MsgBox function determines what appears in the message box.<br />

The Sub procedure that follows is another example of using the MsgBox function:<br />

Sub GetAnswer2()<br />

Msg = “Do you want to process the monthly report?”<br />

Msg = Msg & vbNewLine & vbNewLine<br />

Msg = Msg & “Processing the monthly report will take approximately “<br />

Msg = Msg & “15 minutes. It will generate a 30-page report for all “<br />

Msg = Msg & “sales offices for the current month.”<br />

Title = “XYZ Marketing Company”<br />

Config = vbYesNo + vbQuestion<br />

Ans = MsgBox(Msg, Config, Title)<br />

If Ans = vbYes Then RunReport<br />

If Ans = vbNo Then Exit Sub<br />

End Sub<br />

This example demonstrates an efficient way to specify a longer message in a message box. A variable (Msg)<br />

and the concatenation operator (&) are used to build the message in a series of statements. vbNewLine is a<br />

constant that represents a break character. (Using two line breaks inserts a blank line.) The title argument is<br />

also used to display a different title in the message box. Figure 41.5 shows how this message box appears<br />

when the procedure is executed.<br />

719

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!