问题描述
我有一个包含72个ActiveX组合框的电子表格。理想情况下,当我更改其中一个组合框的值时,我希望将该组合框的名称(或其他唯一标识符)传递给使用该名称/标识符的子例程RespondToChange。例如,如果组合框名为cbXYZ,我会将该名称传递给子例程。我可以使用一些代码,如
Private Sub cbXYZ_Change()
RespondToChange "cbXYZ"
End Sub
但是,这需要为所有72个组合框插入代码,这很繁琐。
有没有一种简单的方法可以检测到哪个组合框已更改并将该信息传递给RespondToChange?
推荐答案
您需要一个全局事件处理程序。查看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或工作表激活时),然后任何组合框在更改时都将激发Class1的cmb_Change
事件。