MS Access 2016 VBA 按钮中的代码重用

MS Access 2016 VBA Code Reuse in Buttons

我有一个包含 16 种不同表单的 Access 数据库前端。它们都有三个共同的按钮,即 Show AllClearRefresh,它们执行的正是使用它们各自的子表单的相同功能。例如,要查看来自名为 tbl_Students 的 table 的数据, 学生表单 [=] 上这些按钮的 'On Click' 事件 有以下代码:

Option Explicit
'Show all records button
Private Sub cmdShowAll_Click()
    Dim task As String
    task = "SELECT * FROM tbl_Students"
    Me.frm_Students_subform.Form.RecordSource = task
    Me.frm_Students_subform.Form.Requery
End Sub

'Clear displayed records button
Private Sub cmdClear_Click()
    Dim task As String
    task = "SELECT * FROM tbl_Students WHERE (StudentID) is null"
    Me.frm_Students_subform.Form.RecordSource = task
    Me.frm_Students_subform.Form.Requery
End Sub

'Refresh records button
Private Sub cmdRefresh_Click()
    Me.frm_Students_subform.Form.Requery
End Sub

目前,我在所有 16 个表单中使用完全相同的代码,但子表单名称不同。有没有更好、更有效的方法来实现代码重用?谢谢

考虑在标准模块中创建一个 通用子例程,所有 16 种形式都调用该子例程传递所需的参数。具体使用CurrentProject and Controls通过字符串动态引用对象

模块 保存在命名的标准模块中(不在任何形式后面)

Option Explicit

Public Sub ProcessForms(task As String, mainform As String, subform As String)
On Error GoTo ErrHandle

    CurrentProject.AllForms(mainform).Controls(subform).Form.RecordSource = task
    CurrentProject.AllForms(mainform).Controls(subform).Requery
    Exit Sub

ErrHandle:
    Msgbox Err.Number & " - " & Err.Description, vbCritical, "RUNTIME ERROR"
    Exit Sub
End Sub

示例表格 单行调用

Option Explicit
'Show all records button

Private Sub cmdShowAll_Click()
    Call ProcessForms("SELECT * FROM tbl_Students", _
                      "frm_students", "frm_Students_subform")
End Sub

'Clear displayed records button
Private Sub cmdClear_Click()
    Call ProcessForms("SELECT * FROM tbl_Students WHERE (StudentID) IS NULL", _
                      "frm_students", "frm_Students_subform")
End Sub

'Refresh records button
Private Sub cmdRefresh_Click()
    ' Re-assigns same recordsource in line with others
    Call ProcessForms(Me.Controls("frm_Students_subform").Form.RecordSource, _
                      "frm_students", "frm_Students_subform")
End Sub