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

时间:2015-01-05 21:50:33

标签: excel vba excel-vba checkbox

我有一个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

1 个答案:

答案 0 :(得分:1)

创建复选框的子退出后,

colCBHandlers将超出范围。

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