Excel VBA add handler to every checkbox in form

淺唱寂寞╮ 提交于 2019-12-13 08:21:55

问题


I have an excel form with a large number of checkboxes that are added at runtime. I would like to add a handler to each one of those checkboxes that will run when the value is changed. I know in other versions of Visual Basic I would use AddHandler, but that doesn't work in Excel VBA.

Following an example, I came up with the following code:

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

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

And, in my userform, I have this code:

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:


colCBHandlers will go out of scope as soon as the sub which creates the checkboxes exits.

You need to declare that collection as a global (at the module level) so it doesn't get lost once it has been created and populated.



来源:https://stackoverflow.com/questions/27788497/excel-vba-add-handler-to-every-checkbox-in-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!