VBA MsgBox

Syntax of MsgBox function in VBA:
The syntax of VBA Msgbox is as follows:

Here ‘Text_String’ is the message that you want the msgbox to display. The maximum length of ‘Text_String’ is 1024 characters.

‘buttons’ parameter specifies the type of buttons and icon that you want to be shown on the message box. It is an optional parameter. If you omit it then msgbox shows the default ‘vbOKOnly’ button.

‘title’ refers to the text displayed in the title bar of message box. This is an optional parameter.

‘helpfile’ is a string parameter that specifies the help file to be used for the dialog box. It is also an optional parameter but it becomes mandatory if ‘context’ parameter is to be used.

‘context’ is a numeric parameter that specifies the number assigned to the appropriate Help topic. It is an optional parameter but it becomes mandatory if ‘helpfile’ parameter is used.

Different values of ‘buttons’ parameter in Msgbox:
In VBA message box, ‘buttons’ parameter can have following values:

Examples of Message boxes in VBA:
Now, let’s move on to some particle examples to understand the use of msgbox:

Example 1: Basic message box:

view plaincopy to clipboardprint?

Sub Msg_exe MsgBox "This is a message!" End Sub Example 2: Message box with a title:

view plaincopy to clipboardprint?

Sub Msg_exe MsgBox "This is a message!",, "This is the Title" End Sub Example 3:  Exclamation message box:

view plaincopy to clipboardprint?

Example 4: Message box with multiple lines

view plaincopy to clipboardprint?

Note 1:  Here ‘vbCrLf’ is the new line character in VBA. It can also be replaced by ‘vbNewLine’.

Example 5: Critical Message box with three buttons

view plaincopy to clipboardprint?

Note 1:  Here I have used two values for the ‘button’ parameter separated by a ‘+’ sign.

Note 2: You will notice that here I have used a variable ‘result’ for accepting the value returned by Msgbox.

Values returned by MsgBox Function:
As I have foretold that VBA MsgBox function returns a value based on the user input. These values can be anyone of the below ones:

How you can decide program flow based on the values returned by Message Box?
In the above table you can see that VBA Msgbox function returns some integer values corresponding to button clicked on the dialog box. You can check this number using an IF Statement or by using a Select case statement.

In the below example I have done the same:

view plaincopy to clipboardprint? So, this was all about the msgbox function in VBA. Do let me know if you have any queries related to the topic.