在不使用用户表单的情况下将事件侦听器添加到程序生成的控件

Add event listeners to procedurally generated controls without using a user form

我有一个电子表格并在列的每个单元格中创建 ListBox 控件。我正在尝试捕获他们选择的内容,但是在运行时生成的控件上捕获事件的示例都涉及使用用户表单,而我没有使用用户表单。我是 VBA 的新手,所以如何重现下面的代码 How to add events to Controls created at runtime in Excel with VBA

Option Explicit


Dim ButArray() As New Class2

Private Sub UserForm_Initialize()
    Dim ctlbut As MSForms.CommandButton

    Dim butTop As Long, i As Long

    '~~> Decide on the .Top for the 1st TextBox
    butTop = 30

    For i = 1 To 10
        Set ctlbut = Me.Controls.Add("Forms.CommandButton.1", "butTest" & i)

        '~~> Define the TextBox .Top and the .Left property here
        ctlbut.Top = butTop: ctlbut.Left = 50
        ctlbut.Caption = Cells(i, 7).Value
        '~~> Increment the .Top for the next TextBox
        butTop = butTop + 20

        ReDim Preserve ButArray(1 To i)
        Set ButArray(i).butEvents = ctlbut
    Next
End Sub

我生成控件的代码是

Public Sub CreateListbox()
 Dim rCell As Range
    Dim rRng As Range
    Set rRng = ActiveSheet.Range("AA3:AA45")
    For Each rCell In rRng.Cells
        Set oLISTBOX = ActiveSheet.OLEObjects.Add(classtype:="Forms.ListBox.1")
With oLISTBOX
        .Object.IntegralHeight = False
        .Object.Font.Size = 11
        .Top = rCell.Top
        .Left = rCell.Left
        .Width = rCell.Width
        .Height = rCell.Height
        .LinkedCell = rCell.Address
        .ListFillRange = "ValSocDeterm."
        .Object.ColumnCount = 3
        .MultiSelect = 1
    End With

    Next rCell
End Sub

我基本上想将在表单上创建按钮的示例代码用于在 Sheet 上创建列表框。

类似于 class 模块,名为 clsCustomListBox,包含以下代码

Option Explicit

Private WithEvents custom As MSForms.ListBox

Public Function initialise(cbConvert As MSForms.ListBox) As Boolean
    Set custom = cbConvert
End Function

Private Sub custom_Click()
    MsgBox "Clicked"
End Sub

然后是一个标准模块,用于遍历 sheet 并获取所有列表框,或者您可以在代码添加列表框时直接添加到集合中。

Option Explicit

Private cls_CustomListBox As clsCustomListbox
Public colCustomListboxCollection As Collection

Public Sub GetListBoxes()

Dim c As OLEObject

Set colCustomListboxCollection = New Collection

For Each c In Worksheets("Sheet1").OLEObjects

    If TypeOf c.Object Is MSForms.ListBox Then
        Set cls_CustomListBox = New clsCustomListbox
        cls_CustomCombo.initialise c.Object
        colCustomListboxCollection.Add c
    End If

Next c

End Sub

我还没有在工作中进行全面测试,但这就是 id 的开始。

希望对您有所帮助。