excel - 从 VBA 中的多个按钮调用相同的 SUB

标签 excel vba

我在同一列但不同行的电子表格上有多个按钮(事件 x)。这些按钮捕获事件的开始时间。
如果按下按钮 1,则它旁边的单元格应由当前时间填充。
如果按下按钮 2,则它旁边的单元格应由当前时间填充。等等.....

我在 VBA 中编写了一个 SUB,如下所示:

Private Sub StartTimer_Click()
    Range("I4").Value = Now
End Sub

我不想为每个按钮操作重复此代码。请让我知道如何使它成为动态的。

最佳答案

一个简单的 WithEvents 示例:
在一个类(名为 clsButtons)中:

Private WithEvents Bt As MSForms.CommandButton

Property Set obj(b As MSForms.CommandButton)
    Set Bt = b
End Property

Private Sub Bt_Click()
    'uses the right of the name of the CommandButton
    Cells(1 + Right(Bt.Name, 1) * 3, 9).Value = Now
End Sub
在工作表代码(带有按钮的那个)中:
Dim myButtons As Collection

Private Sub Worksheet_Activate()
    Dim ctl As OLEObject
    Dim ButtonClass As clsButtons
    Set myButtons = New Collection

    For Each ctl In Sheet1.OLEObjects
        If ctl.progID = "Forms.CommandButton.1" Then
            Set ButtonClass = New clsButtons
            Set ButtonClass.obj = ctl.Object
            myButtons.Add ButtonClass
        End If
    Next ctl
    
End Sub

关于excel - 从 VBA 中的多个按钮调用相同的 SUB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51237250/

相关文章:

Excel VBA,ActiveWorkbook.Save触发了Workbook_BeforeSave事件,但是Workbook_BeforeSave中的代码行通过,没有任何结果

excel - 更改形状的背景颜色

excel - 如何在vba excel中拆分具有多个分隔符的字符串?

vba - 将一行中的每个值复制到另一个值匹配的工作簿?

vba - 运行时错误 424 - 需要对象错误

excel - Excel 中日期的数值错误?

excel - 将字符串转换为 Excel 日期和时间,具有特定的字符串格式

excel - 使用从文本文件导入的范围创建表

excel - VBA 使用字符串参数评估函数

vba - 通过规则删除附件的 Outlook 脚本