Excel VBA 为表单中的每个复选框添加处理程序

Excel VBA add handler to every checkbox in form

我有一个 excel 表单,其中包含大量在运行时添加的复选框。我想为每个复选框添加一个处理程序,这些复选框将在值更改时运行。我知道在其他版本的 Visual Basic 中我会使用 AddHandler,但这在 Excel VBA.

中不起作用

根据示例,我想出了以下代码:

'This is in a class module called CheckboxHandler
Public WithEvents cb As MSForms.CheckBox

Private Sub cb_change()
    MsgBox ("test")
end sub

而且,在我的用户表单中,我有以下代码:

With CreateObject("Scripting.Dictionary")
.....'Unrelated code omitted

'Variable Checkboxes
'Add Handler to checkboxes
Dim colCBHandlers As Collection
Set colCBHandlers = New Collection
Dim objHandler As CheckboxHandler

Dim i As Long
Dim chkBox As MSForms.CheckBox
For i = 1 To .count - 1
    Set chkBox = Me.Controls.Add("Forms.Checkbox.1", "Checkbox" & i)
    chkBox.Caption = .Keys()(i)
    chkBox.VALUE = False
    chkBox.Top = (chkBox.Height + 10) * (i - 1) + 55
    chkBox.Left = 725
    Set objHandler = New CheckboxHandler
    Set objHandler.cb = chkBox
    colCBHandlers.Add objHandler
Next i
End With
一旦创建复选框的子程序退出,

colCBHandlers 将超出范围。

您需要将该集合声明为全局集合(在模块级别),以便它在创建和填充后不会丢失。