18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Part VI<br />

Programming Excel with VBA<br />

To get a response from a message box, you can assign the result of the MsgBox function to a variable. The<br />

following code uses some built-in constants (described in the “Constants That Are Used in the MsgBox<br />

Function” sidebar) to make it easier to work with the values that are returned by MsgBox:<br />

Sub GetAnswer()<br />

Ans = MsgBox(“Continue?”, vbYesNo)<br />

Select Case Ans<br />

Case vbYes<br />

‘ ...[code if Ans is Yes]...<br />

Case vbNo<br />

‘ ...[code if Ans is No]...<br />

End Select<br />

End Sub<br />

When this procedure is executed, the Ans variable contains a value that corresponds to vbYes or vbNo.<br />

The Select Case statement determines the action to take based on the value of Ans.<br />

You can easily customize your message boxes because of the flexibility of the button argument. Table 41.1<br />

lists the built-in constants that you can use for the button argument. You can specify which buttons to display,<br />

whether an icon appears, and which button is the default.<br />

TABLE 41.1<br />

Constants That Are Used in the MsgBox Function<br />

Constant Value Description<br />

vbOKOnly 0 Display OK button.<br />

vbOKCancel 1 Display OK and Cancel buttons.<br />

vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.<br />

vbYesNoCancel 3 Display Yes, No, and Cancel buttons.<br />

vbYesNo 4 Display Yes and No buttons.<br />

vbRetryCancel 5 Display Retry and Cancel buttons.<br />

vbCritical 16 Display Critical Message icon.<br />

vbQuestion 32 Display Warning Query icon.<br />

VBExclamation 48 Display Warning Message icon.<br />

vbInformation 64 Display Information Message icon.<br />

vbDefaultButton1 0 First button is default.<br />

vbDefaultButton2 256 Second button is default.<br />

vbDefaultButton3 512 Third button is default.<br />

718

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

Saved successfully!

Ooh no, something went wrong!