How the Msg Box emulation works

Notice the use of four Public variables. The first three (Promptl, Buttonsl, and Titlel) represent the arguments that are passed to the function. The other variable (UserClick) represents the values returned by the function. The UserForm_ Initialize procedure needs a way to get this information and send it back to the function, and using Public variables is the only way to accomplish that.

The UserForm (shown in Figure 15-7) contains four Image controls (one for each of the four possible icons), three CommandButton controls, and a TextBox control.

0 my msgbox.xls - MyMsgBoxForm (U... W



Microsoft Excel

£1 Sample text

• 1 :

Figure 15-7: The UserForm for the MyMsgBox function.

The code in the UserForm_Initialize procedure examines the arguments and does the following:

♦ Determines which, if any, image to display (and hides the others)

♦ Determines which button(s) to display (and hides the others)

♦ Determines which button is the default button

♦ Centers the buttons in the dialog box

♦ Determines the captions for the CommandButtons

♦ Determines the position of the text within the dialog box

♦ Determines how wide to make the dialog box (by using an Application Programming Interface [API] call to get the video resolution)

♦ Determines how tall to make the dialog box

♦ Displays the UserForm

Three additional event handler procedures are included (one for each CommandButton). These routines determine which button was clicked and return a value for the function by setting a value for the UserClick variable.

Interpreting the second argument (buttons) is a bit challenging. This argument can consist of a number of constants added together. For example, the second argument can be something like:

VbYesNoCancel + VbQuestion + VbDefaultButton3

This argument creates a three-button MsgBox (with Yes, No, and Cancel buttons), displays the Question icon, and makes the third button the default button. The actual argument is 547 (3 + 32 + 512). The challenge was pulling three pieces of information from a single number. The solution involves converting the argument to a binary number and then having the interpreter examine specific bits. For example, 547 in binary is 1000100011. Binary digits 4 through 6 determine the image displayed; digits 8 through 10 determine which buttons to display; and digits 1 and 2 determine which button is the default button.

0 0

Post a comment