【发布时间】:2021-08-29 13:21:06
【问题描述】:
我正在尝试以编程方式将 onClick 事件添加到 VBA 中的命令按钮。我不希望 CommandButton 与表单相关联,因为最终表单应如下所示:
我已经有一个名为 boardButton 的类模块,其中包含一个应在单击按钮时触发的事件:
Public WithEvents button As MSForms.CommandButton
Private Sub button_Click()
MsgBox "You've just clicked the button"
End Sub
还有一个 sub,也在类模块中声明,用于创建按钮:
Private Sub AddButton(ByVal row As Integer, ByVal column As Integer)
Set t = ActiveSheet.Range(Cells(row, column), Cells(row, column))
Set btn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False, Left:=t.Left, Top:=t.Top, width:=t.width, height:=t.height)
Set createdButton = btn.Object
createdButton.Caption = ""
createdButton.BackColor = RGB(121, 195, 232)
Dim gameBoardButton As New boardButton
Set gameBoardButton.button = createdButton
End Sub
我遇到的问题是,每当我单击任何按钮时都不会触发该事件。没有错误,我已经尝试在事件子中使用其他一些代码。我不知道我创建按钮的方式是否正确,以及这是否是未触发点击事件的原因。
我们将不胜感激。感谢您的宝贵时间!
【问题讨论】: