【问题标题】:Single event handler for multiple ComboBox controls in VBAVBA 中多个 ComboBox 控件的单个事件处理程序
【发布时间】:2020-01-04 16:05:11
【问题描述】:

我有一个包含 72 个 activex 组合框的电子表格。理想情况下,当我更改其中一个组合框的值时,我想将该组合框的名称(或其他唯一标识符)传递给使用名称/标识符的子例程 RespondToChange。例如,如果组合框名为 cbXYZ,我会将该名称传递给子例程。我可以使用一些代码,例如

Private Sub cbXYZ_Change()
   RespondToChange "cbXYZ"
End Sub

但是,这需要为所有 72 个组合框插入代码,这很繁琐。

是否有一种简单的方法来检测哪个组合框已更改并将该信息传递给 RespondToChange?

【问题讨论】:

    标签: excel vba combobox


    【解决方案1】:

    您需要一个全局事件处理程序。查看WithEvents

    您可以这样做。


    添加一个新类并将此代码放入该类中。

    Public WithEvents cmb As ComboBox
    Private Sub cmb_Change()
        '/ Do whatever you want to do when the event occurs.
        MsgBox cmb.Name
    End Sub
    

    添加一个模块并将这段代码放入其中。

    Option Explicit
    '/ an array to hold all the comboboxes
    '/ Class1 is the class name. Change if your class name is different.
    Dim comboBoxes() As New Class1
    
        Sub HookEvents()
            Dim lCtr As Long
            Dim cmb
            '/ Sheet1 is sheet's code name. Change accordingly for your sheet's name.
            For Each cmb In Sheet1.OLEObjects
                '/ Loop all controls on the sheet and check it its a combobox.
                If TypeName(cmb.Object) = "ComboBox" Then
                    lCtr = lCtr + 1
                    ReDim Preserve comboBoxes(1 To lCtr)
                    '/ Add to keep it alive
                    Set comboBoxes(lCtr).cmb = cmb.Object
                End If
            Next
        End Sub
    

    确保首先调用 HookEvents(可能在 workbook_open 或工作表激活上),然后任何 ComboBox 在更改时都会触发 Class1 的 cmb_Change 事件。

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      相关资源
      最近更新 更多