[英]VBA Excel Userform EventHandler for dynamically generated controls not working as expected
I'm working in Excel 2013, designing a Userform with controls created at run-time. 我正在使用Excel 2013,设计一个带有在运行时创建的控件的用户窗体。 I'm having trouble making a function that will fire on the change event of the dynamically created controls.
我在制作将在动态创建的控件的change事件上触发的函数时遇到了麻烦。
The controls are contained in a separate class module that creates them and manages them. 控件包含在一个单独的类模块中,该模块创建并管理它们。 I want to add a function that fires on the change event of a combo-box, so I have it declared WithEvents:
我想添加一个在组合框的change事件上触发的函数,因此我将其声明为WithEvents:
Private WithEvents myComboBox As MSForms.ComboBox
... other controls and variable declarations...
I have a function that is passed the frame that I want the controls to be in so that I can create all the components from within the class. 我有一个函数,该函数传递了我想要控件放入的框架,这样我就可以从类中创建所有组件。
Sub initialize(myID As String, myFrame As MSForms.Frame, Left As Double, Top As Double)
...
Set myComboBox = myFrame.Controls.Add("Forms.ComboBox.1", myID & "_comboBox")
...
End Sub
This all works, and the ComboBox is created and properties changed though myComboBox
successfully change how the ComboBox appears. 所有这些都有效,并且尽管
myComboBox
成功更改了ComboBox的显示方式,但创建了ComboBox并更改了属性。
Because myComboBox
is declared WithEvents
, I can find myComboBox_Change
as an option in the drop-down menus and put it in the module: 因为
myComboBox
被声明为WithEvents
,所以我可以在下拉菜单中找到myComboBox_Change
作为选项并将其放在模块中:
Private Sub myComboBox_Change()
MsgBox ("Change Event Fired")
End Sub
But this function will not run, and I can't figure out why. 但是此功能将无法运行,我无法弄清原因。 A messagebox will not appear when a change is made, and breakpoint put in this function will not stop any code from running.
进行更改时,不会出现消息框,并且此函数中的断点不会停止任何代码的运行。 What am I doing wrong?
我究竟做错了什么?
With the help of some probing questions from cyboashu, I figured out what was wrong. 在cyboashu的一些探索性问题的帮助下,我弄清楚了什么地方出了问题。 The class containing
myComboBox
was not held by a variable declared for the scope of the entire userform. 包含
myComboBox
的类不属于为整个用户表单的范围声明的变量。 After the function creating it completed, the components were still in myFrame
, but the functions to be fired on events were forgotten 函数创建完成后,组件仍位于
myFrame
,但是忘记了要在事件上触发的函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.