assigning event handler subs to a dynamically created control?possible? how?

Hi, I want to have some controls existing in any newly created workbooks/worksheets. So I create a combobox when it is necessary with OLEObjects.Add method. But then I want to catch events happening on this control so the Private Sub ComboBox1_Change() procedure should be created for it from a program. Is it possible Strange to me, that I cannot assign an event handler even through the user interface, while it is possible with a combobox created using the controls toolbar. If you know how to assign event handlers in runtime, please let me know! thanks, PEter


Answer this question

assigning event handler subs to a dynamically created control?possible? how?

  • WS_progger_starter

    Per our support engineer:

    After reviewing the case log, it seems that you want to create controls dynamically on Excel worksheets and hook event handler to dynamically created controls.
    Usually it is easier to hook event handler to the dynamically created control on the same form. If you want to do so on another worksheet, try to refer to the following link.
    The following applies to dynamically created control on the same form. You need to declare the control variable initially and set the variable to the dynamically created controls. For example:

    ' need to define "dim WithEvents SecondButton as Commandbutton" outside of any sub or procedure
    dim WithEvents SecondButton as Commandbutton

    Private Sub TestScenarioButton_click()

    ' set variable
    Set Secondbutton = Controls.Add ("Forms.Commandbutton.1")
    Secondbutton.left = 100
    Secondbutton.Top = 100
    Secondbutton.visible = true

    End Sub

    'as SecondButton variable is set to the dynamically created control, the following event will occur
    Private Sub SecondButton_Click()
    Userform1.hide
    End Sub

    http://www.experts-exchange.com/Programming/Programming_Languages/Visual_Basic/Q_20439045.html

    -brenda (ISV Buddy Team)



  • assigning event handler subs to a dynamically created control?possible? how?