Using Msg Box with Yes or No Buttons

MsgBox has other uses apart from output display. For instance, a MsgBox could be used to get the user to make a simple choice of two or more options, and then take appropriate program action depending on the choice made. If the programmer were to customise the layout of the MsgBox to include two buttons taking values Yes, or No, then the statement:

Outcome = MsgBox ("Do you like Bananas?", vbYesNo, "Tastes in fruit question")

would have the effect of producing the output as shown in Figure 3.8. Note how the parenthesis has been placed around the right-hand side following the MsgBox keyword. This is required if you wish to capture the result of the choice given in the message box. In the above example we have captured the result of the MsgBox in the variable Outcome. More will be said about variables in Chapter 5 - all you need to know at this stage is that in the above statement the variable Outcome will store a value, when the user chooses a response from either Yes or No in the message box. It will not actually store 'Yes' or 'No', but instead it will hold coded values as shown in Table 3.2. For example, suppose we wanted to write VBA code that would prompt the user with the MsgBox as shown in Figure 3.8, and respond with a message box stating "Good Taste!" if the user replied with the answer Yes. This would be implemented with the following fragment of VBA code:

Outcome = MsgBox ("Do you like Bananas?", vbYesNo, "Tastes in fruit question")

If (Outcome =6 ) Then MsgBox "Good Taste!"

End If

The statement If (Outcome =6 ) Then checks to see if the value assigned to the variable Outcome is equal to 6, which - as can be seen from Table 3.2 -means choosing the option Yes. If this statement is true, then the MsgBox "Good Taste!" is executed, otherwise it is not. The statement End If terminates the If block. (See Chapter 6 for more on the If statement.)

Figure 3.8 The MsgBox function using Yes/No choices

0 0

Post a comment