简体   繁体   中英

Single event handler for multiple ComboBox controls in VBA

I have a spreadsheet with 72 activex comboboxes. Ideally, when I change the value of one of the comboboxes I would like to pass the name (or other unique identifier) of that combobox to a subroutine RespondToChange that uses the name/identifier. For example, if the combobox is named cbXYZ, I would pass that name to the subroutine. I could use some code such as

Private Sub cbXYZ_Change()
   RespondToChange "cbXYZ"
End Sub

However, this requires inserting code for all 72 comboboxes, which is tedious.

Is there a simple way of detecting which combobox has been changed and passing that information to RespondToChange?

You need a global event handler. Look into WithEvents .

Here's how you could do it.


Add a new Class and put this code inside that class.

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

Add a module and put this code inside it.

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

Make sure you call HookEvents first ( may be on workbook_open or sheet activate) and then any ComboBox, when changed, will fire Class1's cmb_Change event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM