Often times, you may need to create a Yes/No message box in MS Access. In this short tutorial, I’ll show you the steps to create such a box using a VBA.
To start, here is the general VBA structure that you can use to execute a yes/no message box in Access:
If MsgBox("Type your message here", vbYesNo + vbQuestion) = vbYes Then VBA Command to be executed if Yes is selected Else VBA Command to be executed if No is selected End If
Example of a Yes/No Message Box
Now, I’ll review a simple example where I’ll create the following yes/no message box:
As you can see, there are two options to choose from. For our example:
- If the “Yes” option is selected, then the MS Access application will be closed
- Alternatively, if the “No” option is chosen, then no further action will be taken, and you’ll return back to the main Access Form
Steps to Create a Yes/No Message Box
Step 1: Create the MS Access Form
To start, create the MS Access Form, where you’ll be able to add a button.
The goal is to display the following message box when you click on that button:
“Are you sure you want to exit the application?”
First, go the the Create tab, and then click on the Form Design:
You’ll now see the Access Form.
Now add a button to that Form:
You’ll now see the Command Button Wizard. Click on Cancel, as this Wizard will not be needed:
Right-click on the button, and then select the Build Event… option:
Choose the Code Builder option, and then press on OK:
You’ll now see the following screen:
Step 2: Add the VBA to create the Yes/No Message Box
Now add the VBA below in order to create the message box in Access:
If MsgBox("Are you sure you want to exit the application?", vbYesNo + vbQuestion) = vbYes Then DoCmd.Quit Else Exit Sub End If
This is how the full VBA would look like:
Save the Access Form by clicking on CTRL+S. Here, I named the Form as ‘Test’:
Step 3: Run the VBA
To run the VBA, you’ll need to switch to the Form View:
Now, you’ll be able to click on the button on your Form:
You’ll then see the following Box:
- If you click on the Yes option, you’ll exit the application
- Alternatively, if you click on the No option, you’ll return back to the Access Form, and no further action will be taken