excel 单击某个按钮名称,使其触发类模块中的WithEvents

2mbi3lxu  于 2023-04-07  发布在  其他
关注(0)|答案(2)|浏览(132)

在“test”工作表中,我有两个名为btTest1和btTest2的ActiveX按钮。
在“测试”工作表模块中:

Dim MyButtons As Collection

Private Sub Worksheet_Activate()
Set MyButtons = New Collection
For i = 1 To 2
    Set ButtonClass = New ClassTest
    If i = 1 Then Set ButtonClass.obj1 = ActiveSheet.btTest1
    If i = 2 Then Set ButtonClass.obj1 = ActiveSheet.btTest2
    MyButtons.Add ButtonClass
Next
End Sub

在ClassTest类模块中:

Private WithEvents bt As MSForms.CommandButton

Property Set obj1(b As MSForms.CommandButton)
Set bt = b
End Property

Private Sub bt_Click()
MsgBox bt.Caption
End Sub

在我激活“测试”表后,然后单击“测试1”按钮,它显示msgbox“测试1”,当我单击“测试2”按钮时,它显示msgbox“测试2”。

  • 如何编码,所以当“测试”表被激活,然后msgbox“测试1”直接显示,如果有一个用户按字面上的“测试1”按钮?*
gojuced7

gojuced71#

您可以简单地添加:

Me.btTest1.Value = True

到事件代码的末尾。

jq6vz3qz

jq6vz3qz2#

罗里已经完全回答了你的问题,更多的取决于你可能想达到的目标-

'''' worksheet module '''
Option Explicit
Private MyButtons As Collection

Private Sub Worksheet_Activate()
Dim i As Long
Dim ButtonClass As ClassTest

    If MyButtons Is Nothing Then
        Set MyButtons = New Collection
        For i = 1 To 2
            Set ButtonClass = New ClassTest
            If i = 1 Then Set ButtonClass.obj1 = Me.btTest1
            If i = 2 Then Set ButtonClass.obj1 = Me.btTest2
            MyButtons.Add ButtonClass
        Next
    End If
    
    Set ButtonClass = MyButtons(1) ' refer to the first item (a ButtonClass instance) in the collection
    
    ButtonClass.bt_Click  '

End Sub

''' ClassTest '''
Option Explicit
Private WithEvents bt As MSForms.CommandButton

Public Property Set obj1(b As MSForms.CommandButton)
Set bt = b
End Property

Public Sub bt_Click()
MsgBox bt.Caption
End Sub

相关问题