How do we know the sender of the buttons in VBA?

前端 未结 2 560
醉梦人生
醉梦人生 2020-12-07 06:54

I would like to find out the sender of many buttons.

Something like that in C#:

Button b = new Bu         


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-07 07:23

    You have to wire up the button events. You can do so in the Worksheet Activate event handler:

    Dim arrEvents As Collection
    
    Private Sub Worksheet_Activate()
    
    Dim objButtonEvents As ButtonEvents
    Dim shp As Shape
    
    Set arrEvents = New Collection
    
    For Each shpCursor In Me.Shapes
        If shpCursor.Type = msoOLEControlObject Then
            If TypeOf shpCursor.OLEFormat.Object.Object Is MSForms.CommandButton Then
                Set objButtonEvents = New ButtonEvents
                Set objButtonEvents.cmdButton = shpCursor.OLEFormat.Object.Object
                arrEvents.Add objButtonEvents
            End If
        End If
     Next
    
    End Sub
    

    Then make a Class Module named ButtonEvents with this code:

    Public WithEvents cmdButton As MSForms.CommandButton
    
    Private Sub cmdButton_Click()
     MsgBox cmdButton.Caption & " was pressed!"
    End Sub
    

提交回复
热议问题