给命令按钮添加点击事件

Add click event to CommandButton

我正在尝试以编程方式将 onClick 事件添加到 VBA 中的命令按钮。我不希望 CommandButton 与表单相关联,因为最后 sheet 应该看起来像这样:

我已经有一个名为 boardButton 的 class 模块,其中包含一个应在单击按钮时触发的事件:

Public WithEvents button As MSForms.CommandButton

Private Sub button_Click()
    MsgBox "You've just clicked the button"
End Sub

还有一个 sub,也在 class 模块中声明,用于创建按钮:

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

我遇到的问题是无论何时单击任何按钮都不会触发事件。没有错误,我已经尝试在事件子中使用其他一些代码。我不知道我创建按钮的方式是否正确,是否这就是未触发点击事件的原因。

帮助将不胜感激。感谢您的宝贵时间!

请尝试下一个方法:

  1. 将下一个声明置于标准模块之上(在声明区域):
Private gameBoardButton(0) As New boardButton
  1. 请使用下改编Sub:
Private Sub AddButton(ByVal row As Integer, ByVal column As Integer)
    Dim t as Range, btn as OleObject, createdButton as Object, i as Long
    If Ubound(gameBoardButton) = 0 then
       i = 0
    Else
       Redim Preserve gameBoardButton(ubouond(gameBoardButton) + 1)
       i = ubouond(gameBoardButton) + 1
    End If
    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)
    
    Set gameBoardButton(i).button = createdButton
End Sub
  1. 按原样使用您的class。

基本上您应该在模块级别声明一个数组变量并在按钮创建期间填充它。然后,最好养成声明所有使用的变量的习惯。

代码未经测试,但这是基本思路。如果您遇到任何错误,请随时提出并寻求帮助...