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

时间:2015-11-25 12:37:04

标签: excel vba commandbutton

我有一个电子表格,并在列的每个单元格中创建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上创建ListBoxes。

1 个答案:

答案 0 :(得分:0)

类似于类模块,名为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

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

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开始的地方。

希望它有所帮助。