WithEvents for Toggle Button VBA

时间:2014-11-22 00:58:09

标签: vba togglebutton userform

我是vba的新手,需要为游戏制作32个切换按钮。我想利用withevents让切换按钮的代码完全相同。我不确定如何做到这一点,并查看类似的问题,但他们没有意义。非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

使用WithEvent进程的第一步是将所有必需的对象添加到collect中以保留在内存中以供将来使用。 UserForm初始化时执行此步骤。

在名为UF的UserForm中:

Option Explicit

Dim ToggleControl As ToggleGroup
Dim Toggles As Collection

Private Sub UserForm_Initialize()
Dim oEach As Object

    Set Toggles = New Collection
    With UF
        For Each oEach In .Controls                        ' Loop through all the controls on the form
            If TypeName(oEach) Like "ToggleButton" Then    ' Verify that the object is a ToggleButton
                Set ToggleControl = New ToggleGroup        ' Create a new class object to assign the ToggleButton to
                Set ToggleControl.Action = oEach           ' Assign the ToggleButton (oEach) to the desired Class Action (Action)
                Toggles.add ToggleControl                  ' Add the Class to a collection to be preserved in memory
            End If
        Next oEach
    End With
End Sub

接下来,您需要向项目添加一个类并将其命名为ToggleGroup。

enter image description here

在名为ToggleGroup的类中:

Option Explicit

Public WithEvents Action As MSForms.ToggleButton

Private Sub Action_Click()

    ' Perform Action ...

End Sub

这将在单击对象时为该对象创建自定义事件。这些自定义事件在本机事件之前执行,这意味着所有本机控制事件仍然有效。