更新时间:2023-11-30 16:01:04
如果您只想添加按钮并捕获点击,则可以为其分配一个通用宏,并切换哪些操作基于按钮的名称(在创建时您将设置它的名称,以及可以通过调用过程中的 Application.Caller
访问)。
Sub AddButtons()
With ActiveSheet.Buttons.Add(100,100,50,50)
.Name =button1
.OnAction =ClickHandler
End with
With ActiveSheet.Buttons.Add(200,100,50,50)
.Name =button2
.OnAction =ClickHandler
结束
End Sub
Sub ClickHandler()
Dim bName As String
bName = Application.Caller
选择案例bName
案例button1:MsgBox点击第一个按钮
案例button2:AnotherSub
结束选择
End Sub
Is there any way to define event procedures for form controls such as the case with ActiveX objects?
I have a GUI which currently adds/removes ActiveX command buttons by the user but ran into Error 91 when trying to add an item to a global collection with each button added. My best guess is because of this much hated phenomenon. With the current state of the project, my best option is to switch to using form control buttons if I am able to define their event procedures. If not, I may need to somehow save the global variables and read them back after manipulating ActiveX control objects.
If you just want to add buttons and capture clicks, you can assign a common macro to them, and switch what action is taken based on the name of the button (which you would set when you create it, and which can be accessed via Application.Caller
in the called procedure)
Sub AddButtons()
With ActiveSheet.Buttons.Add(100, 100, 50, 50)
.Name = "button1"
.OnAction = "ClickHandler"
End With
With ActiveSheet.Buttons.Add(200, 100, 50, 50)
.Name = "button2"
.OnAction = "ClickHandler"
End With
End Sub
Sub ClickHandler()
Dim bName As String
bName = Application.Caller
Select Case bName
Case "button1": MsgBox "Clicked First button"
Case "button2": AnotherSub
End Select
End Sub