如何在VBA中dynamic创buildcombobox创buildSub?

我对excel编程和VBA很陌生。 我卡在一个点,我有随机数dynamic创build的combobox(ComboBox1,ComboBox2 …. ComboBoxN)。 我需要实现一个function,如果我在ComboBox [i](其中我可以是1到N之间的任意数字)中select一个值,那么它应该触发一个事件,将在ComboBox [i + 1]中填充值。

我如何为此编写一个Sub? 有没有其他的方式来实现,如果不是在一个小组?

为了创build一个组事件,你需要一个自定义的类来捕获事件( ObjectListener ),公共variables来保持类的引用(通常是一个集合或数组 – ComboListener )和一个macros来填充集合( AddListeners_ComboBoxes )。

Workbook_Open()调用AddListeners_ComboBoxesmacros。 如果代码中断,您将需要再次调用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 

在这里输入图像说明

类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 

作为Thomas Inzina所展示的“阶级”方法的一个替代scheme,这是一种“不太结构化”的方法:

 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