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.

  1. Using MsgBox to Display Messages in VBA Macros
  2. Displaying Message Boxes
  3. Joining Bits of a Message Together
  4. Customising your Message Box
  5. Using MsgBox to Ask Questions (this blog)

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.

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?

Message box with yes and no buttons

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:

MsgBox as command

Here MsgBox is used as a command

We have instead:

MsgBox as Function

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:

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





'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!

This blog has 0 threads Add post