【发布时间】:2020-05-11 19:23:50
【问题描述】:
我动态创建了许多按钮(创建计划),并希望所有按钮在 Click 事件(OnClick 属性)期间都做同样的事情。
当然,我可以预先在表单上创建最大数量的按钮并将它们设置为不可见,等等,同时考虑到可能有超过一千个按钮,在他们的 Click 事件中添加“调用 SomeEvent”。这将非常乏味。
因此,简化:
我创建了新类 btnClass`
Public WithEvents ButtonEvent As MsForms.CommandButton
Private Sub ButtonEvent_Click()
MsgBox "hey"
End Sub
然后,在我的 UserForm 中,我动态地创建按钮,我添加了这个(我也有 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
但是当我点击动态创建的按钮时没有任何反应。我错过了什么?
---更新 ---@FaneDuru 提供了对我有用的解决方案
ReDim Buttons(0 To btnCount, 0 To dtDiff)
For labelcounter = 0 To dtDiff 'add date labels
Set theLabel = Controls.Add("Forms.Label.1", "lblDay" & labelcounter, True)
With theLabel
.Caption = VBA.Format(DateAdd("d", labelcounter, bDate), "d-mm-yy")
.Left = 15 + 44 * labelcounter
.BackColor = vbBlack
.Font.Bold = True
.ForeColor = vbWhite
.Height = 13
.Width = 40
.Top = 85
End With
For i = 0 To btnCount 'add time buttons
pTime = DateAdd("n", i * dur, begTime)
Set theButton = Controls.Add("Forms.CommandButton.1", "btn" & CDate(theLabel.Caption & " " & TimeValue(pTime)), True)
With theButton
.Height = 17
.Caption = VBA.Format(TimeValue(pTime), "hh:mm")
'.Caption = CDate(theLabel.Caption & " " & TimeValue(pTime))
.Left = 15 + 44 * labelcounter
.BackColor = vbGreen
.Width = 40
.Top = 100 + 18 * i
End With
Set Buttons(i, labelcounter).ButtonEvent = theButton
btnColl.Add theButton, theButton.Name
Next i
Next labelcounter
【问题讨论】:
标签: excel vba events onclick handler