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
Search our website
We also send out useful tips in a monthly email newsletter ...
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.
This blog is part of our Excel macros online tutorial series. Our main business is running training courses in Excel, courses in VBA and training in many other Microsoft applications.
|
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:
Sub SaveCurrentWorkbook()
'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
ActiveWorkbook.Save
Else
'otherwise, just leave the subroutine, perhaps?
Exit Sub
End If
End Sub
The combination of symbols and buttons we choose is as follows:
Choice | Why |
---|---|
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 |
---|
|
Some other pages relevant to the above blogs include:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2023. All Rights Reserved.