[英]Single event handler for multiple ComboBox controls in VBA
I have a spreadsheet with 72 activex comboboxes.我有一个包含 72 个 activex 组合框的电子表格。 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.
理想情况下,当我更改组合框之一的值时,我希望将该组合框的名称(或其他唯一标识符)传递给使用名称/标识符的子程序 RespondToChange。 For example, if the combobox is named cbXYZ, I would pass that name to the subroutine.
例如,如果组合框命名为 cbXYZ,我会将该名称传递给子例程。 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.但是,这需要为所有 72 个组合框插入代码,这很乏味。
Is there a simple way of detecting which combobox has been changed and passing that information to RespondToChange?是否有一种简单的方法来检测哪个组合框已更改并将该信息传递给 RespondToChange?
You need a global event handler.您需要一个全局事件处理程序。 Look into WithEvents .
查看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.确保首先调用
HookEvents
(可能在 workbook_open 或 sheet activate 上),然后任何 ComboBox 在更改时都会触发 Class1 的cmb_Change
事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.