VBA MsgBox function

The VBA MsgBox function is used to display a message box with a specified message and various options, such as buttons and icons. This function is often used to provide information to the user or to prompt them for input.

Syntax of the MsgBox function

MsgBox(prompt, [buttons], [title], [helpfile], [context])

  • prompt: Required. The message you want to display in the message box.
  • buttons: Optional. Specifies which buttons to display in the message box. You can use constants like vbOKOnly, vbYesNo, vbRetryCancel, etc. The default value is vbOKOnly.
  • title: Optional. Sets the title of the message box.
  • helpfile: Optional. Specifies the Help file to be used for the message box.
  • context: Optional. Specifies the Help context number.

How to use the MsgBox function

MsgBox "Hello, this is a simple message box."
MsgBox "Do you want to continue?", vbYesNo + vbQuestion, "Confirmation"
MsgBox "The file was saved successfully.", vbInformation, "Success"

The MsgBox function returns an integer value, which indicates the button that the user clicked. For example, if the user clicks the “Yes” button, the MsgBox function will return the integer value vbYes.

You can use the return value of the MsgBox function to control the flow of your VBA code. For example, you could use the following code to display a message box and then take different actions depending on which button the user clicked:

Dim result As Integer
result = MsgBox(
"Do you want to save your changes?",
vbYesNo + vbQuestion, "Confirmation")
If result = vbYes Then
Else
End If