VBA Function: MsgBox

The VBA MsgBox function displays a dialog box that prompts the user to click a button and returns the corresponding integer value of the clicked button.

Usage:

MsgBox(prompt)

or

MsgBox(prompt, buttons, title)


Example of Usage

Asking for confirmation before performing an action only if the user clicked the Yes button:

Sub example()
    
    choice = MsgBox("Confirm deletion?", 36, "Confirmation")
    
    'If the user clicked the Yes button
    If choice = vbYes Then
        MsgBox "You clicked Yes!", 64
    End If
    
End Sub

You may notice that this example uses the MsgBox function twice.

The first dialog box asks the user to confirm their choice and saves the choice in the choice variable:

choice = MsgBox("Confirm deletion?", 36, "Confirmation")
excel vba msgbox function confirm deletion

The second dialog box is displayed for informational purposes (i.e., the button clicked by the user is irrelevant this time). To avoid unnecessary handling of the return value from the function, it is used as a procedure (without parentheses) in this case:

MsgBox "You clicked Yes!", 64
excel vba msgbox function confirmation

List of buttons and return values

You can find more detailed explanations on the dialog boxes page of the VBA course.