559 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owls only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Using MsgBox to Display Messages in VBA Macros
Part five of a five-part series of blogs
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.
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.
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!
|Parts of this blog|
25 Aytoun Street