VBA MsgBox
The MsgBox function shows a popup with a message, buttons, and an icon. Different arguments can be provided to the Buttons argument to show different buttons and icons. The MsgBox function returns a member of the VbMsgBoxResult enum which indicates which button was pushed by the user.
Syntax:
MsgBox(Prompt,[Buttons As VbMsgBoxStyle=vbOKOnly],[Title],[HelpFile],[Context]) As VbMsgBoxResult
VbMsgBoxStyle
The Buttons parameter of the MsgBox function can be passed constants from the VbMsgBoxStyle enum which determine which type of buttons and icon the message box will have. A button style can be joined with an icon style by adding the constants together.
Public Sub Example()
MsgBox "Hello, World!", vbOKOnly + vbInformation
End Sub
Constant | Value | Description |
---|---|---|
vbOKOnly | 0 | OK button only |
vbOKCancel | 1 | OK and Cancel buttons |
vbAbortRetryIgnore | 2 | Abort, Retry, and Ignore buttons |
vbYesNoCancel | 3 | Yes, No, and Cancel buttons |
vbYesNo | 4 | Yes and No buttons |
vbRetryCancel | 5 | Retry and Cancel buttons |
vbCritical | 16 | Critical Message icon (Red "x" circle) |
vbQuestion | 32 | Warning Query icon (Blue "?" circle) |
vbExclamation | 48 | Warning Message icon (Yellow "!" triangle) |
vbInformation | 64 | Information Message icon (Blue "i" circle) |
vbDefaultButton1 | 0 | First button is default |
vbDefaultButton2 | 256 | Second button is default |
vbDefaultButton3 | 512 | Third button is default |
vbDefaultButton4 | 768 | Fourth button is default |
vbApplicationModal | 0 | The application is suspended until the message box is dismissed |
vbSystemModal | 4096 | All applications are suspended until the message box is dismissed |
vbMsgBoxHelpButton | 16384 | Help button is added to the message box |
vbMsgBoxSetForeground | 65536 | Sets the message box window as the foreground window |
vbMsgBoxRight | 524288 | Right-aligns text |
vbMsgBoxRtlReading | 1048576 | Specifies right-to-left reading on Hebrew and Arabic systems |
VbMsgBoxResult
The MsgBox function returns a value from the VbMsgBoxResult enum which represents the button clicked by the user.
Public Sub Example()
Dim Result As VbMsgBoxResult
Result = MsgBox("Yes or No?", vbYesNo + vbQuestion)
Select Case Result
Case vbYes
Debug.Print "Yes was clicked."
Case vbNo
Debug.Print "No was clicked."
End Select
End Sub
Constant | Value |
---|---|
vbOK | 1 |
vbCancel | 2 |
vbAbort | 3 |
vbRetry | 4 |
vbIgnore | 5 |
vbYes | 6 |
vbNo | 7 |