How to add event handling to a control from a dynamically loaded OCX library in Excel VBA

StackOverflow https://stackoverflow.com/questions/14055810

  •  12-12-2021
  •  | 
  •  

Pregunta

In an Excel 2003 VBA project, I am using the TreeCtrl from MSCOMCTL.OCX. I add the control dynamically to a form in my application (see code below).

I would like to handle the NodeClick event of the TreeCtrl.

Since the control is added dynamically, just using TreeCtrl_NodeClick does not seem to work. Also I cannot use the WithEvents approch since it does not seem to work with types which are not known at compile time.

'Does not work. WithEvents probably only works on known data types that have events.
'private WithEvents treeCtrl As Object 

'This code adds the control to the form
Private Sub UserForm_Initialize()
    Dim treeCtrl As Object
    Set treeCtrl = Me.Controls.Add("MSComctlLib.TreeCtrl.2", "MyTreeCtrl")
    'Does not work: AddHandler is not available in VBA.
    'AddHandler TreeCtrl.NodeClick, AddressOf UserForm1.MyTreeCtrl_NodeClick 
End Sub

'This is supposed to be the event handler but it does not get called.
Private Sub MyTreeCtrl_NodeClick(ByVal Node As Object) 
    MsgBox "Node clicked"
End Sub

Note that I need to load MSCOMCTL.OCX dynamically. I cannot put it as a static reference into my VBA project (since my project has to run in different versions of Excel).

¿Fue útil?

Solución

According to this response from MS "you cannot handle the events for a TreeView control added in runtime using Excel VBA", although there is a suggested workaround using VB6(!).

Is adding the control at design-time and then hiding it until required an option?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top