Microsoft Access: Call a Public Sub or Function From a Button
Question details
The user wants to call VBA code from a Microsoft Access command button and understand why changing a Public Function to a Public Sub causes an error.

- Product
- Microsoft Access
- Device & OS
- not provided
- Scenario
- A command button's On Click property uses the expression =OpenCal() to open a calendar form.
- Observed behavior
- The expression works with a Public Function but reports that the function cannot be found when OpenCal is changed to a Public Sub.
Open the form in Design View and select the command button. In the Property Sheet, check the On Click setting on the Event tab and locate the OpenCal procedure in the VBA editor.
Keep OpenCal as a Public Function for the button expression
Use this approach when you want to keep =OpenCal() in the button's On Click property.
Access event expressions can evaluate Functions but cannot directly call Subs. The Function does not need to return a useful value for this action.
Press Alt+F11 and find OpenCal in a standard module. If needed, choose Insert > Module to create one.
Define the procedure as: Public Function OpenCal() DoCmd.OpenForm "Cal" End Function. Replace Cal with the name of your form if it differs.
Return to the form in Design View, select the button, and enter =OpenCal() in Property Sheet > Event > On Click.
Save the form, switch to Form View, and click the button to check that the Cal form opens.

Call the Public Sub from a button event procedure
Use an event procedure when OpenCal should remain a Sub rather than a Function.
Use WPS Office for everyday Office documents
WPS Office is a free, lightweight alternative with a familiar interface for working with documents, spreadsheets, and presentations. It supports common Microsoft Office formats for easier migration, but it does not fix Access button events or replace an Access database.

Frequently Asked Questions
Why does =OpenCal() fail when OpenCal is a Sub?
The On Click expression evaluates a Function, not a Sub. Change OpenCal back to a Public Function, or set On Click to [Event Procedure] and call the Sub from VBA.
Does the Function need to return a value?
No useful return value is required when the Function is used to perform an action such as DoCmd.OpenForm "Cal". It can still be called with =OpenCal() in the On Click property.
Where do I add the call to a Public Sub?
Select the button in Design View, set On Click to [Event Procedure], and click the adjacent build button (...). Add OpenCal inside the generated Click procedure.
Can I open the form without a separate OpenCal procedure?
Yes. Set the button's On Click property to [Event Procedure], open the code with the build button (...), and add DoCmd.OpenForm "Cal" inside the Click procedure.




