Inserting messagebox (MsgBox) vba code
MsgBox function is the simplest way to communicate and interact with the user and therefore is much used.
A MsgBox is used to:
- Communicate information, a warning or an error message;
- Ask the user a question.
|In some cases it is better to create dedicated userforms, which give better support to more complex user interaction with a combination of choices and the use of list boxes and other controls. Implementing a userform however is quite a bit of work.|
Using MsgBox in combination with Select Case
In many cases the msgbox, in addition to providing information, is used to ask the user to make a decision concerning the further flow of the program.
For example, if a contact does not exist, does he want to create a new one. The appropriate way to handle this is in a
block where the different cases reflect to possible returned values of the MsgBox function. These values are from the VbMsgBoxResult enumeration,
but are determined by the value of the
Buttons argument. In the example below the value vbYesNoCancel indicates the user has three possible choices.
Select Case MsgBox(Prompt:="Do you want to create a new contact", _ Buttons:=vbYesNoCancel + vbQuestion + vbDefaultButton2, _ Title:="Manage contacts") Case vbYes Case vbNo Case vbCancel End Select
Use the Code VBA add-in to insert MsgBox code
The Code VBA add-in makes it a breeze to insert MsgBox code including the appropriate Select Case block.
Click this to see the insertion of msgboxcode using code vba.
MsgBox Buttons argument
The Buttons argument type is
VbMsgBoxStyle. This is the result of a combination of choices you can make with regard to
- Which buttons are available;
- Which button is preselected - if any;
- If an icon is to be displayed in the dialog.
In the above example:
Buttons:=vbYesNoCancel + vbQuestion + vbDefaultButton2 meaning:
- Include buttons for Yes, No and Cancel;
- Make the second button the Default.
- Adorn the dialog with the Question mark icon.
Add icon to dialog to convey the purpose of the interaction
Adding an icon to dialog to convey the purpose of the interaction makes you program more use friendly and makes it look nicer.
The following icons can be used by including the appropriate constant to the