没有具体命名请参考Form Control

Refer to Form Control Without Specific Naming

我有一个包含大量图像的表单,单击时每个图像都会执行一系列操作。我可以为每个按钮创建一个包含所有操作的 Private Sub,但我认为这是低效的。相反,我想将所有操作记录在一个宏中,然后在单击每个图像时调用此宏。为此,我需要单个宏来引用当前选择的图像,而不是按名称引用任何图像。这可能吗?

我当前的代码包括以下内容:

Me.Image001.BorderColor = RGB(1, 1, 1)
Me.Image001.BorderWidth = 2
Me.Image001.BorderStyle = 1

我需要对此进行修改,以便修改所选图像的边框 colour/width/style 等,而不是特定命名图像 ('Image001')。

谢谢!

您始终可以创建标准子程序,然后单击按钮调用它。像

Public Sub changeColor(frm As Form, ctrl As Control)
    frm.Controls(ctrl.Name).BorderColor = RGB(1, 1, 1)
    frm.Controls(ctrl.Name).BorderWidth = 2
    frm.Controls(ctrl.Name).BorderStyle = 1
End Sub

因此,当您单击图片时,您所要做的就是,

Private Sub Image001_Click()
    changeColor Me, Image001
End Sub

你应该使用事件接收器。
使用事件下沉,您可以将自己的过程绑定到事件。 您可以在此处查看示例 http://p2p.wrox.com/access-vba/37472-event-triggered-when-any-control-changed.html
简而言之,您创建了一个模块,您可以在其中将事件绑定到您的特定实现。然后在您感兴趣的表单上创建一个集合,在其中注册您想要 "follow" 事件下沉的控件...
我的 sub sinking for checkboxes(我有很多)
第一个 class 模块名称 SpecialEventHandler

Option Compare Database

Private WithEvents chkbx As CheckBox
Private m_Form As Form
Private Const mstrEventProcedure = "[Event Procedure]"

Public Function init(chkbox As CheckBox, frm As Form)
  Set chkbx = chkbox
  Set m_Form = frm
  'Debug.Print frm.Name
  chkbx.AfterUpdate = mstrEventProcedure
End Function

Private Sub chkbx_AfterUpdate()
  'your Code here
End Sub



Private Sub Class_Terminate()
    Set chkbx = Nothing
    Set m_Form = Nothing
End Sub

然后在你要使用事件下沉的表单上

Option Compare Database
Dim spEventHandler As SpecialEventHandler
Private colcheckBoxes As New Collection

Private Sub Form_Open(Cancel As Integer)
  Dim ctl As Control

  For Each ctl In Me.Detail.Controls
  Select Case ctl.ControlType

    Case acCheckBox
        Set spEventHandler = New SpecialEventHandler
        spEventHandler.init Controls(ctl.NAME), Me
        colcheckBoxes.Add spEventHandler
    End Select
Next ctl
End Sub