In Microsoft Access VBA, use MsgBox to show a message or ask a user a question; combine button and icon constants with Or, then check the returned value when the answer matters. For example, MsgBox "Saved successfully.", vbInformation, "Save" displays an information icon and a window titled Save.
What MsgBox Does in Access VBA
MsgBox displays a dialog box containing a prompt, optional buttons, and an optional title. It pauses the running VBA procedure until the user responds, so it is useful for short notices, simple warnings, and decisions that should be made before code continues. It is not a way to create a permanent message on an Access form, and it is not a replacement for a detailed data-entry form.
In Access, you can call it from code in a form, report, or standard module. A common use is a button’s Click event: show a confirmation, then continue only if the user selects Yes. A message box can also display a validation warning, such as asking someone to fill in a required field. Keep prompts clear about what happened or what the user is being asked to do.
A message box is modal: the user must respond to it before returning to the calling procedure. That makes it suitable for an important, immediate prompt, but intrusive if it appears repeatedly or interrupts a long-running task. For routine status updates, a form label or other interface element may be less disruptive.
Basic Syntax and Button Constants
The function’s general syntax is MsgBox(prompt, buttons, title, helpfile, context). Only the prompt is required. The buttons argument can combine a button layout, an icon, a default-button choice, and a modality setting. The title is optional; if omitted, VBA supplies a default caption. The help-file and context arguments are for linking a dialog to a help topic and are rarely needed in everyday Access applications.
Common button-layout constants include:
vbOKOnlydisplays OK;vbOKCanceldisplays OK and Cancel.vbYesNodisplays Yes and No;vbYesNoCanceladds Cancel.vbAbortRetryIgnoreandvbRetryCancelprovide other built-in layouts for appropriate situations.
Common icon constants are vbInformation, vbQuestion, vbExclamation, and vbCritical. Choose an icon that matches the meaning rather than using a warning symbol for every message. You can set the initially selected button with vbDefaultButton1, vbDefaultButton2, and the corresponding third or fourth button constants where the layout supports them. For example, vbDefaultButton2 is useful when the safer answer should be selected by default.
Combine these values with Or, as in vbYesNo Or vbQuestion Or vbDefaultButton2. The constants are numeric values designed to be combined; do not add them as ordinary arithmetic. Use the named constants rather than memorizing numbers, because the names make the intention of the code easier to review.
Simple MsgBox Examples
This procedure displays a short information message. It has a declared procedure and uses the optional title argument:
Public Sub ShowSavedMessage()
' Tell the user the save step completed.
MsgBox "The record was saved.", vbInformation, "Save complete"
End Sub
For a longer prompt, join text with vbCrLf to place a line break between sentences. The underscore continues a VBA statement on the next line:
Public Sub ShowExportWarning()
' Use a line break to keep the prompt readable.
MsgBox "The export did not complete." & vbCrLf & _
"Check the destination folder and try again.", _
vbExclamation, "Export"
End Sub
Line breaks can make a message easier to scan, but they do not make a dialog suitable for a long explanation. If users need several instructions, consider placing them on a form or in a help page instead.
Ask a Question and Use the Return Value
When VBA needs to act on the user’s choice, assign the result of MsgBox to a variable. A useful variable type is VbMsgBoxResult. For a Yes/No layout, the returned values are vbYes and vbNo; other layouts return values such as vbOK, vbCancel, or vbRetry.
Public Sub ConfirmRecordAction()
Dim answer As VbMsgBoxResult
' Make No the default to reduce accidental confirmation.
answer = MsgBox("Continue with this action?", _
vbYesNo Or vbQuestion Or vbDefaultButton2, _
"Please confirm")
If answer = vbYes Then
' Place the intended action here.
MsgBox "You chose Yes.", vbInformation, "Choice"
ElseIf answer = vbNo Then
MsgBox "No changes were made.", vbInformation, "Choice"
End If
End Sub
The example deliberately does not delete or modify a record: the comment marks where application-specific work would go. A confirmation dialog only asks for consent; it does not itself protect data or reverse an operation. If the operation is destructive, verify the correct record and use an appropriate recovery plan as well as a clear prompt.
For a three-button layout, test all possible results. With vbYesNoCancel, users may choose Cancel or close the dialog, so code should not assume that the answer is always Yes or No. Treat cancellation as a decision to stop unless the application’s workflow explicitly requires another behavior.
Choosing a Prompt, Icon, and Default
A strong prompt names the action and, where helpful, its consequence. “Delete the selected order?” is more informative than “Are you sure?” If the action affects a particular record, include a safe identifier, such as an order number, rather than relying on a vague reference to “this.” Avoid including sensitive information that should not be exposed on screen.
- Use
vbInformationfor a neutral completion notice, not as proof that an operation succeeded unless the code has confirmed success. - Use
vbExclamationfor a warning that needs attention, andvbCriticalfor a serious error condition. - Use
vbQuestionfor a decision prompt, with button labels that fit the actual choices. - Choose a default button deliberately. Make the safer or less consequential choice the default when an accidental Enter key press could cause harm.
Built-in message boxes have fixed button labels and a limited layout. You cannot use MsgBox to create arbitrary button text such as “Keep draft” and “Submit,” or to add check boxes and custom controls. A custom Access form is a better choice when the decision needs tailored labels, extra context, or more than a simple response.
Where to Put the Code in an Access Database
For a message tied to a form button, put the procedure in that form’s module and connect it to the button’s Click event. In the form’s Design View, select the button, open the Property Sheet, and use the Event tab to set On Click to [Event Procedure]. Use the build button beside the property to open the VBA editor for that event. The exact ribbon layout can vary slightly with Access versions, but the event property is the key connection.
A reusable procedure that is not tied to one form can go in a standard module. A form-specific procedure can refer to that form’s controls, while a standard module should not assume a particular form is open unless the code checks that condition. For example, a required-name warning might be placed in a form event that runs before saving; the code should validate the actual control or field and then prevent saving if the value is missing.
Test the event in a copy of the database before relying on it in normal use. Save a separate copy of the Access database before running VBA: actions initiated by code cannot be undone with Ctrl+Z. This matters especially if the code writes, deletes, or updates records.
Common Problems and How to Fix Them
- The message appears, but the code continues down the wrong branch. Store the function result and compare it to the matching named constant, such as
vbYes. Do not compare the result to the word “Yes” or assume the first button always returns the same value across different layouts. - The title or buttons are missing. Check the order of the arguments. The second positional argument is the button/options value and the third is the title. A title supplied as the second argument is interpreted as a button value, not a caption.
- The dialog interrupts the user too often. Review whether the message is inside a loop or an event that fires repeatedly. A single summary or a form-based status indicator may be more appropriate than many modal pop-ups.
- Text is hard to read. Shorten the prompt, add a line break with
vbCrLfwhere useful, and use a meaningful title. Avoid displaying raw technical error details to ordinary users without context. - The VBA does not run. Confirm the event is actually connected to the procedure, that the database’s VBA project compiles, and that the file’s macro content is permitted by the organization’s security settings. Do not enable all macros indiscriminately; use trusted files and follow your organization’s policy.
One frequent misconception is that an icon constant or a message-box title changes the operation itself. These values only affect the dialog’s presentation. Similarly, clicking Yes does not automatically save, delete, or validate anything: the code after the result check must perform the intended task, and it should handle errors from that task separately.
MsgBox Compared with Access Alternatives
Use MsgBox for a brief, immediate message or a small set of built-in choices. It is quick to write and does not require designing another form. However, its fixed buttons, modal behavior, and limited layout make it a poor fit for multi-step decisions or messages that users need to read while continuing work.
An Access form can show custom wording, buttons, input fields, and additional explanation. A form is also appropriate when a message should remain visible without blocking other tasks. Access macros can use message-related actions as a no-code alternative for simple workflows, while VBA is more flexible when the response must control branching logic. Choose based on the complexity of the interaction, not just on which option produces the fewest lines of code.
Frequently Asked Questions
How do I show a message in Access VBA?
Call MsgBox with a prompt, and optionally provide button or icon constants and a title. For example, MsgBox "Update complete.", vbInformation, "Status" displays a titled information dialog.
How do I make an Access MsgBox show Yes and No?
Pass vbYesNo as part of the buttons argument, usually combined with an icon such as vbQuestion. Assign the returned value to a variable and test whether it equals vbYes or vbNo.
How do I get the button clicked from MsgBox?
Use the function’s return value. Declare a variable as VbMsgBoxResult, assign the result of the call to it, and compare it with constants such as vbOK, vbCancel, vbYes, or vbNo.
Can I change the text on MsgBox buttons?
No. The built-in VBA message box offers standard button layouts with fixed labels. Create a custom Access form if your workflow needs specific button wording, extra controls, or a more detailed explanation.
Why does my MsgBox code not show when I click a button?
Check that the button’s On Click property is set to [Event Procedure] and that its event procedure contains the call. Also check for compile errors and database security restrictions that prevent VBA from running.
Related
- Excel Shortcut Keys Practice: Drills That Build Speed
- Excel Zoom Shortcuts: How to Zoom In and Out Quickly
- Excel Shortcut Keys for Switching Between Worksheets
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA: How to Find an Accredited VA PractitionerIf by VBA you mean the U.S. Department of Veterans Affairs’ Veterans Benefits Administration, use VA’s official accreditation…
- Excel UserForm: Change Font Size at Design Time or in VBATo change an Excel VBA UserForm’s font size, select the form or a control in the Visual Basic…
- Excel VBA: Find the Bottom Row of Data in a SheetTo find the bottom row in a particular Excel column, start at the worksheet’s last row and move…
- VBA Check If a Worksheet Is Open in ExcelExcel does not open worksheets independently: a worksheet belongs to a workbook that is open in Excel. To…
- Excel VBA: Delete a Range of Rows by Number or MatchTo delete worksheet rows with Excel VBA, use Rows("3:7").Delete for rows 3 through 7, or qualify the range…
- Excel VBA Reset Error Handling: What Err.Clear DoesTo turn off an active VBA error handler in the current procedure, use On Error GoTo 0. Use…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.