我在同一列但不同行的电子表格上有多个按钮(事件 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/