如何使用VBA在ActiveX列表框上执行事件处理

问题描述 投票:0回答:1

使用设计器,我在工作表上创建了几个列表框,而不是为每个列表框编写一个子控件来处理单击(等),我想在一个子控件中处理此列表。

我已经读到,应该可以使用一个类并将现有的列表框分配给该类的事件处理程序,这是可能的。但是我无法正常工作。

a)创建一个类~~~~ CListBoxEventHandler ~~~~包含在类模块工作表中

Public WithEvents CmdEvents As MSForms.ListBox

Private Sub CmdEvents_Click()
    MsgBox "Click Event"
End Sub

b)在工作表上

Private lisHandlers() As CListBoxEventHandler

sub worksheet_activate()
    Dim numObjects As Long: numObjects = Me.OLEObjects.count
    ReDim lisHandlers(1 To numObjects) As CListBoxEventHandler
    dim i as integer: i = 0

    Dim ctrl As OLEObject
    For Each ctrl In Me.OLEObjects
        Dim progID As String: progID = ctrl.progID
        If (progID = "Forms.ListBox.1") Then
            i = i + 1
            Dim myListBox As MSForms.ListBox: Set myListBox = ctrl.Object
            myListBox.LinkedCell = ""
            Set lisHandlers(i).CmdEvents = myListBox
        End If
    Next ctrl
    Redim Preserve lisHandlers(1 to i) as CListBoxEventHandler

end sub

How should I do it and can I do the same with TextBoxes?

Also: cab I use ~~~~ myListBox.OnAction = "ListBox_Change" ~~~~ for each of the listboxes and distinguish between the listboxes by Application.Caller?

excel vba listbox event-handling activex
1个回答
0
投票

您尚未创建任何实例CListBoxEventHandler创建该类型的数组只是为您提供了对Nothing的一组引用,而不是实例化对象的数组。

未经测试:

Private colHandlers As Collection 'easier than an array...

sub worksheet_activate()
    Dim numObjects As Long,  ctrl As OLEObject
    Dim myListBox As MSForms.ListBox, obj As CListBoxEventHandler

    Set colHandlers = New Collection

    For Each ctrl In Me.OLEObjects
        If (ctrl.progID = "Forms.ListBox.1") Then
            Set myListBox = ctrl.Object
            myListBox.LinkedCell = ""
            Set obj = New CListBoxEventHandler
            Set obj.CmdEvents = myListBox
            colHandlers.Add obj
        End If
    Next ctrl

end sub
© www.soinside.com 2019 - 2024. All rights reserved.