Accessing Event Procedures of Form Controls with VBA in Excel

落花浮王杯 提交于 2019-12-11 19:48:50

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/10725754/accessing-event-procedures-of-form-controls-with-vba-in-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!