VBA MsgBox: Complete Guide with Examples (2025)

Updated: January 20259 min read

Quick Answer: MsgBox is a VBA function that displays a dialog box with a message, optional buttons (OK, Yes/No, etc.), and icons. It returns a value indicating which button was clicked. Syntax: MsgBox(prompt, buttons, title)

What is VBA MsgBox?

MsgBox is a built-in VBA function that displays a pop-up dialog box to communicate with users. It's one of the most commonly used functions in VBA for showing messages, asking questions, and getting simple yes/no responses.

Common Uses for MsgBox:

  • Display Information: Show results, confirmations, or status updates
  • Ask Questions: Get yes/no or OK/Cancel responses from users
  • Show Warnings: Alert users about potential issues or errors
  • Debugging: Display variable values while testing macros

Simple MsgBox Example:

Sub SimpleMsgBox()
    MsgBox "Hello, World!"
End Sub

This displays a basic message box with "Hello, World!" and an OK button.

MsgBox vs InputBox

MsgBox:

Displays a message and returns which button was clicked (OK, Yes, No, etc.)

InputBox:

Displays a prompt and returns text that the user types

Use MsgBox for notifications and yes/no questions. Use InputBox when you need text input from users.

MsgBox Syntax and Parameters

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

prompt (Required)

The message text to display. Maximum 1024 characters.

MsgBox "This is the message"

buttons (Optional)

Numeric value specifying button types, icon style, and default button. Default is vbOKOnly (0).

MsgBox "Continue?", vbYesNo + vbQuestion

title (Optional)

Text displayed in the title bar. Default is "Microsoft Excel".

MsgBox "Done!", vbOKOnly, "Success"

helpfile & context (Optional)

Rarely used. Specify a help file and context ID for the Help button.

Complete Example with All Parameters:

Sub FullSyntaxExample()
    Dim result As VbMsgBoxResult
    
    result = MsgBox("Save changes before closing?", _
                    vbYesNoCancel + vbQuestion, _
                    "Confirm Save")
    
    If result = vbYes Then
        ' Save and close
    ElseIf result = vbNo Then
        ' Close without saving
    Else
        ' Cancel - do nothing
    End If
End Sub

This example shows all commonly-used parameters and how to capture the return value.

MsgBox Button Types

The buttons parameter determines which buttons appear in the message box. You can combine button constants with icon constants using the + operator.

vbOKOnly

0

Displays only an OK button (default)

MsgBox "Task completed!", vbOKOnly

vbOKCancel

1

Displays OK and Cancel buttons

result = MsgBox("Proceed?", vbOKCancel)

vbYesNo

4

Displays Yes and No buttons

result = MsgBox("Continue?", vbYesNo)

vbYesNoCancel

3

Displays Yes, No, and Cancel buttons

result = MsgBox("Save?", vbYesNoCancel)

vbRetryCancel

5

Displays Retry and Cancel buttons

result = MsgBox("Retry?", vbRetryCancel)

vbAbortRetryIgnore

2

Displays Abort, Retry, and Ignore buttons

result = MsgBox("Error!", vbAbortRetryIgnore)

Quick Reference Table:

ConstantValueButtons Displayed
vbOKOnly0OK
vbOKCancel1OK, Cancel
vbAbortRetryIgnore2Abort, Retry, Ignore
vbYesNoCancel3Yes, No, Cancel
vbYesNo4Yes, No
vbRetryCancel5Retry, Cancel

MsgBox Icon Types

Add icons to your message boxes by combining icon constants with button constants using the + operator.

vbInformation

64

Information icon (ℹ️)

MsgBox "Process complete!", vbOKOnly + vbInformation

vbExclamation

48

Warning icon (⚠️)

MsgBox "Warning: Data will be deleted!", vbOKCancel + vbExclamation

vbCritical

16

Error icon (❌)

MsgBox "Error: File not found!", vbOKOnly + vbCritical

vbQuestion

32

Question icon (❓)

MsgBox "Continue?", vbYesNo + vbQuestion

Combining Buttons and Icons:

Sub CombineButtonsAndIcons()
    Dim result As VbMsgBoxResult
    
    ' Yes/No with Question icon
    result = MsgBox("Save changes?", vbYesNo + vbQuestion, "Confirm")
    
    ' OK/Cancel with Warning icon
    result = MsgBox("This cannot be undone!", vbOKCancel + vbExclamation, "Warning")
    
    ' OK only with Error icon
    MsgBox "Operation failed!", vbOKOnly + vbCritical, "Error"
    
    ' OK only with Info icon
    MsgBox "Task completed successfully!", vbOKOnly + vbInformation, "Success"
End Sub

MsgBox Return Values

When users click a button, MsgBox returns an integer value indicating which button was clicked. Store this value in a variable to determine the user's response.

Return Value Constants:

ConstantValueButton Clicked
vbOK1OK
vbCancel2Cancel
vbAbort3Abort
vbRetry4Retry
vbIgnore5Ignore
vbYes6Yes
vbNo7No
Sub CheckReturnValue()
    Dim result As VbMsgBoxResult
    
    result = MsgBox("Delete this file?", vbYesNo + vbQuestion, "Confirm Delete")
    
    If result = vbYes Then
        MsgBox "File deleted!", vbInformation
    Else
        MsgBox "Delete cancelled.", vbInformation
    End If
End Sub

Best Practices:

  • Always declare result variable as VbMsgBoxResult for clarity
  • Use named constants (vbYes, vbNo) instead of numbers (6, 7)
  • Handle all possible return values in your If statements
  • Don't store return value if using vbOKOnly (no choice to make)

8 Practical MsgBox Examples

Example 1: Simple Notification

Sub SimpleNotification()
    MsgBox "Data import completed successfully!"
End Sub

Use case: Show completion messages or status updates

Example 2: Yes/No Confirmation

Sub ConfirmAction()
    Dim result As VbMsgBoxResult
    
    result = MsgBox("Are you sure you want to delete all data?", _
                    vbYesNo + vbQuestion, "Confirm Delete")
    
    If result = vbYes Then
        ' Delete data
        Range("A:Z").ClearContents
        MsgBox "Data deleted.", vbInformation
    End If
End Sub

Use case: Confirm destructive actions before proceeding

Example 3: Multi-line Message

Sub MultiLineMessage()
    Dim message As String
    
    message = "Report Summary:" & vbNewLine & vbNewLine
    message = message & "Total Sales: $50,000" & vbNewLine
    message = message & "Total Orders: 150" & vbNewLine
    message = message & "Average Order: $333"
    
    MsgBox message, vbOKOnly + vbInformation, "Monthly Report"
End Sub

Use case: Display formatted reports or multi-line information

Example 4: Error Handling

Sub ErrorHandlingExample()
    On Error GoTo ErrorHandler
    
    ' Your code here
    Dim x As Integer
    x = 1 / 0  ' This will cause an error
    
    Exit Sub
    
ErrorHandler:
    MsgBox "Error: " & Err.Description, vbCritical, "Error Occurred"
End Sub

Use case: Display error messages to users

Example 5: Display Variable Values

Sub DisplayVariables()
    Dim userName As String
    Dim userAge As Integer
    
    userName = "John"
    userAge = 30
    
    MsgBox "Name: " & userName & vbNewLine & "Age: " & userAge, _
           vbOKOnly + vbInformation, "User Info"
End Sub

Use case: Debug macros by showing variable values

Example 6: Save Before Close

Sub SaveBeforeClose()
    Dim result As VbMsgBoxResult
    
    result = MsgBox("Do you want to save changes before closing?", _
                    vbYesNoCancel + vbQuestion, "Save Changes")
    
    Select Case result
        Case vbYes
            ActiveWorkbook.Save
            ActiveWorkbook.Close
        Case vbNo
            ActiveWorkbook.Close SaveChanges:=False
        Case vbCancel
            ' Do nothing - stay open
    End Select
End Sub

Use case: Prompt to save before closing workbooks

Example 7: Validation Check

Sub ValidateInput()
    If Range("A1").Value = "" Then
        MsgBox "Please enter a value in cell A1!", _
               vbExclamation, "Validation Error"
        Range("A1").Select
        Exit Sub
    End If
    
    ' Continue with processing
    MsgBox "Validation passed!", vbInformation
End Sub

Use case: Validate user input before processing

Example 8: Progress Notification

Sub ProcessWithNotification()
    Dim i As Long
    Dim totalRows As Long
    
    totalRows = Cells(Rows.Count, 1).End(xlUp).Row
    
    ' Process data
    For i = 1 To totalRows
        ' Your processing code here
    Next i
    
    MsgBox "Processed " & totalRows & " rows successfully!", _
           vbOKOnly + vbInformation, "Process Complete"
End Sub

Use case: Notify users when long processes complete

Frequently Asked Questions

What is MsgBox in VBA?

MsgBox is a built-in VBA function that displays a message box dialog to users. It can show messages, ask questions, and return values based on which button the user clicks. It's one of the most commonly used functions in VBA for user interaction.

What's the difference between MsgBox and InputBox?

MsgBox displays a message and returns which button was clicked (OK, Yes, No, etc.), while InputBox displays a prompt and returns text that the user types. Use MsgBox for notifications and yes/no questions, and InputBox when you need text input from users.

How do I create a Yes/No message box in VBA?

Use MsgBox with the vbYesNo constant: result = MsgBox("Continue?", vbYesNo). Then check if result = vbYes or result = vbNo to determine which button was clicked.

What are the MsgBox button types?

VBA MsgBox supports several button types: vbOKOnly (just OK button), vbOKCancel (OK and Cancel), vbYesNo (Yes and No), vbYesNoCancel (Yes, No, and Cancel), vbRetryCancel (Retry and Cancel), and vbAbortRetryIgnore (Abort, Retry, and Ignore).

How do I add an icon to a MsgBox?

Add icon constants to the buttons parameter: vbInformation (info icon), vbQuestion (question mark), vbExclamation (warning icon), or vbCritical (error icon). Example: MsgBox "Error!", vbOKOnly + vbCritical

Can I customize the MsgBox title?

Yes, use the third parameter: MsgBox "Message", vbOKOnly, "Custom Title". If you don't specify a title, it defaults to "Microsoft Excel".

How do I create a multi-line message in MsgBox?

Use vbNewLine or Chr(10) to create line breaks: MsgBox "Line 1" & vbNewLine & "Line 2". You can also use vbCrLf for carriage return and line feed.

What does MsgBox return?

MsgBox returns an integer value indicating which button was clicked: vbOK (1), vbCancel (2), vbAbort (3), vbRetry (4), vbIgnore (5), vbYes (6), or vbNo (7). Store this in a variable to check the user's response.

Need Help Creating VBA Code?

Our AI-powered VBA Code Generator creates working VBA code from plain English descriptions. No coding knowledge required!

✓ No credit card required ✓ 5 free generations ✓ Instant results

Related Articles