Search code examples
vbams-access

How do I call a a Sub from multiple On Click events in Access VBA?


I have a List Form in Access with 7 data fields visible on the form. When the user clicks any one of these fields I want it to run the same sub without any differences based on which one they click. I have it currently set up that each one has their own On Click event that goes to the sub, but I was wanting a cleaner way to handle it.

The code they all run opens a form.

Sub Gage_Load()
    On Error GoTo ErrorHandler
    
    Dim ID As Variant
    
    ' Ensure that the Table_ID field contains a value before proceeding
    If IsNull(Me.Table_ID) Then
        MsgBox "No record selected or Gage ID is Null. This can happen if the data has not been refreshed in awhile. Please refresh and try again.", vbExclamation, "Error"
        Exit Sub
    End If

    ID = Me.Table_ID
    DoCmd.OpenForm "Gage_Modify", , , , , , ID

    Exit Sub

ErrorHandler:
    MsgBox "An error occurred: " & Err.Description, vbCritical, "Error"
End Sub

Solution

  • If you change your Gage_Load procedure from a subroutine to a function, you could then set the On Click properties of those data controls to =Gage_Load()

    That approach is simpler (less overhead) than creating VBA event procedures for each of them. However, I'm not sure if you will consider it clean enough.