[英]Call same SUB from multiple buttons in 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
創建一個標准模塊並將程序放在那里。
雖然可以在私有模塊中共享過程,但最佳做法是將任何共享過程放在共享模塊中。
在 VBA 編輯器中單擊Insert
> Module
,
粘貼到那里,並給它一個唯一的名字。 使用您的示例,您可以執行以下操作:
Public Sub SetTimeValue()
Range("I4").Value = Now
End Sub
...然后從你的另一個調用這個公共存根,比如:
Private Sub StartTimer_Click()
SetTimeValue
End Sub
...以及從您需要調用代碼的任何其他位置。
我假設您所關心的實際過程有不止一行代碼,否則重復復制它並不是真正的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.