如何在VBA中动态创建ComboBox上创建Sub?

时间:2016-09-18 08:06:53

标签: excel vba excel-vba combobox

我是excel编程和VBA的新手。我陷入了一个点,我有随机数量的动态创建的组合框(ComboBox1,ComboBox2 .... ComboBoxN)。 我需要实现一个功能,如果我在ComboBox [i]中选择一个值(其中我可以是1到N之间的任何随机数),那么它应该触发一个将填充ComboBox [i + 1]中的值的事件。

我如何为此写一个Sub?如果不是在Sub中,还有其他方法可以实现吗?

2 个答案:

答案 0 :(得分:3)

为了创建组事件,您需要一个自定义类来捕获事件(ObjectListener),公共变量以使类引用保持活动状态(通常是集合或数组 - ComboListener)和一个宏来填充集合(AddListeners_ComboBoxes)。

AddListeners_ComboBoxes调用Workbook_Open()宏。如果代码中断,您将需要再次致电AddListeners_ComboBoxes

标准模块

Public ComboListener As Collection

Sub AddListeners_ComboBoxes()
    Dim ws As Worksheet
    Dim obj As OLEObject
    Dim listener As ObjectListener

    Set ComboListener = New Collection

    For Each ws In Worksheets
        For Each obj In ws.OLEObjects
            Select Case TypeName(obj.Object)
            Case "ComboBox"
                Set listener = New ObjectListener
                Set listener.Combo = obj.Object

                ComboListener.Add listener
            End Select
        Next
    Next
End Sub

enter image description here

Class ObjectListener

Option Explicit

Public WithEvents Combo As MSForms.ComboBox

Private Sub Combo_Change()
    MsgBox Combo.Name
    Select Case Combo.Name
        Case "ComboBox2"
        ActiveSheet.OLEObjects("ComboBox3").Object.ListIndex = 1

    End Select

End Sub

答案 1 :(得分:0)

作为" Class"的替代品。托马斯·因兹纳(Thomas Inzina)所展示的方法是“结构较差”#34;的方法:

Private Sub ComboBox1_Change()
    PopulateCombo 2
End Sub

Private Sub ComboBox2_Change()
    PopulateCombo 3
End Sub

Private Sub ComboBox3_Change()
    PopulateCombo 4
End Sub

Private Sub ComboBox4_Change()
    PopulateCombo 1 '<--| will "last" combobox populate the "first" one?
End Sub

Private Sub PopulateCombo(cbNr As Long)
    With ActiveSheet.OLEObjects("ComboBox" & cbNr) '<--| reference the combobox as per the passed number
        .ListFillRange = "Sheet1!J1:J10" '<--| populate it with "Sheet1" worksheet range "A1:A10"
        .Object.ListIndex = 1 '<--| select its first item
    End With
End Sub