Access VBA uses the built-in MsgBox function to show a message and, optionally, buttons, an icon, and a title. Its vb constants make those choices readable: for example, vbYesNo Or vbQuestion displays a question with Yes and No buttons, and the function returns a constant such as vbYes to tell your code what the user chose.
What MsgBox does and how its syntax works
A message box is a small, modal dialog: the user must respond to it before continuing with the current code or returning to the Access interface. In an Access VBA procedure, the function has this general form:
MsgBox(prompt, buttons, title, helpfile, context)
Only prompt is required. It is the message text. The optional buttons argument accepts one button-group constant, optionally combined with an icon, a default-button choice, and certain display options. title supplies the caption shown in the dialog’s title bar. The last two arguments connect the dialog to a help file and a context identifier; most everyday prompts do not need them.
The function can be used as a statement when you only need to display information, as in MsgBox "Record saved.", vbInformation, "Save complete". If the user’s choice matters, assign the result to a variable. The result is a VbMsgBoxResult value, which you can compare with constants such as vbYes or vbCancel.
Common button and icon constants
The button group determines which response choices appear. Choose one group; do not combine two different button groups. The standard groups are:
vbOKOnly(0): one OK button. This is also the default if you omit the button group.vbOKCancel(1): OK and Cancel.vbAbortRetryIgnore(2): Abort, Retry, and Ignore.vbYesNoCancel(3): Yes, No, and Cancel.vbYesNo(4): Yes and No.vbRetryCancel(5): Retry and Cancel.
An icon can help signal the nature of the prompt, but it does not change what the code does. The common icon constants are vbCritical (16), vbQuestion (32), vbExclamation (48), and vbInformation (64). For instance, an informational notice can use vbOKOnly Or vbInformation. Pick an icon that accurately reflects the message; an alarming icon for a routine update can make an application feel less clear rather than safer.
These names are preferable to typing their numeric values. A reader can understand vbYesNo at a glance, while the number 4 does not explain whether it represents buttons, an icon, or something else. The values are useful when diagnosing old code, but normally there is no reason to replace the named constants with numbers.
Combining styles and choosing a default button
The buttons argument is a bit field: separate style choices are combined with the VBA Or operator. In practice, combine one button group with at most one icon and, when useful, one default-button constant. The first, second, third, and fourth button can be selected as the default with vbDefaultButton1 (0), vbDefaultButton2 (256), vbDefaultButton3 (512), and vbDefaultButton4 (768).
For example, vbYesNo Or vbQuestion Or vbDefaultButton2 presents a question with Yes and No choices and makes No the initially selected button. A default button is the one activated by pressing Enter; it is not a restriction on the user’s choice. Choosing a cautious default can be sensible for a consequential confirmation, but do not rely on the default alone to protect data. Make the prompt explicit and test the returned result.
Some additional style constants exist for less common needs. vbApplicationModal (0) is the normal modality: the user must answer before continuing in the application. vbSystemModal (4096) makes the dialog system-modal and is generally inappropriate for ordinary Access prompts. vbMsgBoxHelpButton (16384) adds a Help button; supplying a help file and context is necessary for useful help navigation. Right-aligned text and right-to-left reading are available through vbMsgBoxRight and vbMsgBoxRtlReading. Use special display flags only when the application’s interface genuinely calls for them.
Understanding the return value
Button-style constants describe what to display; return constants describe what the user selected. They are separate concepts, even when their numeric values overlap. The common results are vbOK (1), vbCancel (2), vbAbort (3), vbRetry (4), vbIgnore (5), vbYes (6), and vbNo (7).
Compare the result with the matching named return constant, not with the numeric value of a button group. For a Yes/No prompt, test for both vbYes and vbNo as appropriate. For a Yes/No/Cancel prompt, handle all three outcomes explicitly. Treating every result other than No as Yes can accidentally interpret Cancel as consent, which is a common logic mistake.
For readability, declare a variable as VbMsgBoxResult when storing the answer. This makes the purpose of the variable clear to a future maintainer and helps distinguish a dialog result from unrelated integers in the procedure.
A safe confirmation example in Access VBA
This example asks whether to continue with a hypothetical operation. It demonstrates a title, an icon, a non-first default choice, and checking the result. It deliberately does not delete or modify a record; put the real operation only in the branch where the intended response has been checked.
Before running any VBA procedure that changes data, save a copy of the Access database. VBA changes cannot be undone with Ctrl+Z, so test data-changing code on a copy first.
Public Sub AskBeforeContinuing()
Dim answer As VbMsgBoxResult
' Ask for confirmation; No is the default choice.
answer = MsgBox("Continue with this operation?", _
vbYesNo Or vbQuestion Or vbDefaultButton2, _
"Confirm operation")
If answer = vbYes Then
' Place the intended operation here after testing it safely.
MsgBox "You chose Yes.", vbInformation, "Selection"
ElseIf answer = vbNo Then
MsgBox "No changes were requested.", vbInformation, "Selection"
End If
End Sub
The line-continuation character, a space followed by an underscore, lets the argument list span multiple lines. You can also build a multi-line prompt with vbCrLf, the VBA constant for a carriage return and line feed. For example, a prompt can put a short explanation and a question on separate lines without making the code depend on a particular form control.
Using MsgBox in an Access application
Access VBA code can call MsgBox from a standard module, a form’s module, or an event procedure such as a button’s On Click event. Constants like vbYesNo and vbInformation are part of VBA’s standard environment; they are not Access field names and should not be typed into a table or query as if they were data.
Keep the message concise and tell the user what action is being confirmed. A prompt such as “Continue?” gives little context if several forms or tasks are open. “Close this order without saving the changes?” explains the consequence more clearly. If the procedure changes a record, make sure the code’s actual behavior matches the wording and that Cancel or No leaves the data in the intended state.
Access also has a MsgBox action in the macro designer. That is a separate macro action with its own settings; VBA expressions and constants are used in VBA code, not pasted indiscriminately into macro-design fields. If a macro needs branching based on a response, plan how its conditions and values are represented in that macro, or use a VBA event procedure when that makes the decision logic clearer.
Common mistakes and troubleshooting
- Using a style constant as the answer.
vbYesNoselects buttons;vbYesis a possible return value. Store the function’s result and compare it with the latter. - Combining button groups. Select exactly one group, such as
vbOKCancelorvbYesNo. Add an icon or default-button style withOr, rather than adding another button group. - Using a button constant in the wrong argument. The second argument is the style setting and the third is the title. If the title appears as a number or the wrong buttons appear, check argument order.
- Ignoring Cancel. A prompt that offers Cancel must have a defined Cancel path. In particular, do not write an If statement that treats every non-No answer as approval.
- Expecting a message box to undo a change. It only displays a prompt and returns a choice. It does not roll back a database edit that has already occurred.
- Seeing “Variable not defined” for a misspelled constant. Check the spelling and whether the code is actually in a VBA procedure. A constant typed as plain text into a macro or query is not automatically interpreted as a VBA constant.
If you are unsure which constants are available in the VBA editor, use its Object Browser to inspect the VBA library and the VbMsgBoxStyle or VbMsgBoxResult enumerations. This is also useful when maintaining older code that uses numeric style values and you want to replace them with readable names.
When to use a form instead
MsgBox is a good fit for a brief notice or a simple choice among standard buttons. It is not designed for a form-like interaction with text boxes, a list of records, several independent choices, or custom validation. An Access form gives you more control over layout, labels, accessibility, and what happens when the user presses a button.
A custom form is also easier to adapt when the message depends on record details or needs to display several pieces of context. The trade-off is additional design and code: for a simple “saved” notice, a message box is usually simpler. Choose the smallest interface that communicates the decision and handles each response reliably.
Frequently Asked Questions
What is the VBA constant for Yes and No buttons?
Use vbYesNo in the buttons argument. To read the choice, assign the MsgBox result and compare it with vbYes or vbNo.
How do I add an information icon to an Access MsgBox?
Combine the button group with vbInformation, for example vbOKOnly Or vbInformation. The icon changes the dialog’s visual cue, not the result returned by the function.
What does vbOKOnly mean?vbOKOnly displays a single OK button. It is the default button group, so it can be omitted when that is all the dialog needs.
Can I use vb constants in an Access macro?
VBA constants are intended for VBA expressions. Access’s macro designer has a separate MsgBox action and configuration; do not assume that a VBA code expression can be entered as a macro setting unchanged.
How do I make No the default response?
For a Yes/No prompt, combine vbDefaultButton2 with vbYesNo, such as vbYesNo Or vbQuestion Or vbDefaultButton2. Still check the returned value in code instead of assuming the user accepts the default.
Related
- Power Query Not Equal: Use the <> Operator
- AI Data Validation Tools: Uses, Limits, and How to Choose
- Conditional Formatting Greyed Out? Excel Fixes
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Find a Value in an Array: Loop, Match, and TipsTo find a value in a VBA array, loop from LBound to UBound and compare each element with…
- VBA Add Worksheet After the Last SheetTo add a worksheet after the last sheet tab in Excel, use Worksheets.Add with the last item in…
- Using MsgBox in VBA: Syntax, Buttons, and Return ValuesIn Excel VBA, use MsgBox to show a pop-up message or ask a user a simple question. Call…
- Pivot Table Styles VBA: Apply, Change, and TroubleshootIn Excel VBA, set a PivotTable’s TableStyle2 property to a built-in style name, such as PivotStyleMedium9, to apply…
- Visual Basic: Add a Comment to an Excel Cell with VBAYes. In Excel for Microsoft 365 on Windows, use VBA’s Range.AddComment method to add a note to a…
- Excel VBA: Open a Worksheet by Name or IndexTo open a worksheet in Excel VBA, activate it with a statement such as ThisWorkbook.Worksheets("Data").Activate; replace Data with…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.