Class for Custom Button Event Handling

后端 未结 1 1035
南旧
南旧 2021-01-22 18:58

1) I have a Form with some buttons (its in Access, but I guess it applies for Excel as well).

2) I have a custom class that helps me debug that form (and future forms t

1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-22 19:42

    You can't handle events from a collection. The easiest solution is to use a separate class to handle the button events, make a collection of those classes in your multiple buttons handler, and pass the button from the class handling the single button to the class handling multiple ones on an event.

    Class CSingleButton

    Public buttonsHandler As CButtons
    Public WithEvents btn As Access.CommandButton
    
    Private Sub btn_Click()
        buttonsHandler.HandleClick btn
    End Sub
    

    Class CButtons

    Private ButtonHandlers As Collection
    
    Const MODE_DEBUG As Boolean = True
    
    Public Sub LoadButtons(ByRef TheForm As Access.Form)
    
        Dim ctl As Control
        Dim btnHandler As CSingleButton
        Set ButtonHandlers = New Collection
        For Each ctl In TheForm.Controls
            If ctl.ControlType = acCommandButton Then
                Set btnHandler = New CSingleButton
                Set btnHandler.btn = ctl
                Set btnHandler.buttonsHandler = Me
                ctl.OnClick = "[Event Procedure]"
                ButtonHandlers.Add btnHandler
            End If
        Next ctl
    
    End Sub
    
    Public Sub HandleClick(btn As Access.CommandButton)
        If MODE_DEBUG Then debug.print btn.Name & "_Click"
    End Sub
    

    0 讨论(0)
提交回复
热议问题