使用一个事件处理程序处理多个UserForm控件-VBA Excel

问题描述 投票:0回答:1

我动态创建了许多按钮(创建时间表),并希望它们在Click事件(OnClick属性)中都做同样的事情。

当然,我可以事先在表单上创建最大数量的按钮并将其设置为不可见,依此类推,同时考虑到可能有上千个按钮,请在其Click事件上添加“ call SomeEvent”。这将非常乏味。

因此,简化了:

我创建了新类btnClass`

Public WithEvents ButtonEvent As MsForms.CommandButton
Private Sub ButtonEvent_Click()
    MsgBox "hey"
End Sub

然后,在我的用户窗体中,我在其中动态创建按钮,我以简化形式添加了它(我也有Collection,以便稍后删除按钮):

Dim btnColl As Collection
Dim Buttons As New btnClass

Set btnColl = New Collection
Set Buttons = New btnClass

For i = 0 To btnCount

         Set theButton = Controls.Add("Forms.CommandButton.1", "btn" & i, True)
         With theButton
            .Height = 17
            .Caption = "btn" & i
          End With


        Set Buttons.ButtonEvent = theButton
        btnColl.Add theButton, theButton.Name


Next i

但是当我单击动态创建的按钮时,什么也没有发生。我想念什么?

excel vba events onclick handler
1个回答
0
投票

这样,仅为最后创建的按钮分配事件。您必须声明一个类的数组...我还用了新创建的按钮的Left属性,只是为了测试它们的click事件。请尝试下一种方法:

Option Explicit

Private btnColl As New Collection
Dim Buttons() As New btnClass

Private Sub btCreate_Click()
 Dim btnCount As Long, theButton As CommandButton, i As Long

 btnCount = 3
 ReDim Buttons(0 To btnCount)
 For i = 0 To btnCount

         Set theButton = Me.Controls.aDD("Forms.CommandButton.1", "btn" & i, True)
         With theButton
            .height = 17
            .Caption = "btn" & i
            .left = 50 * i
          End With

        btnColl.aDD theButton, theButton.Name
        Set Buttons(i).ButtonEvent = theButton
 Next i
End Sub

Private Sub btdelete_Click() 'buttons deletion...
 Dim i As Long
   For i = 1 To btnColl.count
       Me.Controls.Remove (btnColl(i).Name)
   Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.