BLOGS BY TOPIC▼
BLOGS BY AUTHOR▼
BLOGS BY YEAR▼
The MsgBox command in Visual Basic for Applications allows you to display basic messages, but you can also make it prettier, and even use it to ask questions or display multiple-line messages! Read on to find out more about this versatile VBA command.
- Using MsgBox to Display Messages in VBA Macros
- Displaying Message Boxes
- Joining Bits of a Message Together
- Customising your Message Box
- Using MsgBox to Ask Questions (this blog)
Posted by Andy Brown on 28 September 2011
You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.
Using MsgBox to Ask Questions
Everything in this blog so far has concentrated on displaying a message on screen (we haven't been interested in the button the user chooses). But how about this?
This message box allows you to choose YES or NO - the code then detects the button chosen and acts accordingly.
In this case we use MsgBox as a function, not a command. So instead of:
Here MsgBox is used as a command
We have instead:
Here MsgBox is used as a function
Confused? Us too. Even though it's the same word MsgBox, the syntax is very different. The rule is that if you use brackets, you must store the return value in a variable.
The Code to Use MsgBox as a Function
Here is a typical routine to get a message box to appear as a question:
'variable to hold the number of the button chosen
Dim ButtonChosen As Integer
'display message box on screen, with YES and NO buttons
ButtonChosen = MsgBox("Do you want to continue?", vbQuestion + vbYesNo + vbDefaultButton2, "Continue?")
If ButtonChosen = vbYes Then
'if the user wants to continue, do something here (here we've
'chosen to save the current workbook
'otherwise, just leave the subroutine, perhaps?
The combination of symbols and buttons we choose is as follows:
|vbQuestion||To get a nice question mark symbol appearing!|
|vbYesNo||To get two buttons to appear: Yes and No|
|vbDefaultButton2||To make sure that if a user chooses Enter, they will by default choose No, not Yes|
And that is the full story on the MsgBox command-cum-function!