Iva*_*nyi 12 excel events vba excel-vba
是否有可能以编程方式创建event method一个comboBox?
在工作表上我有一个ComboBox,我可以通过代码得到它的名字:
Dim ole As OLEObject
For Each ole In ActiveSheet.OLEObjects
If TypeName(ole.Object) = "ComboBox" Then
' ole.Name '<<<<<<<< here
End If
Next ole
Run Code Online (Sandbox Code Playgroud)
我现在如何创建和分配event methodfor ole.Name:
Private Sub myComboBox_Change()
...
End Sub
Run Code Online (Sandbox Code Playgroud)
在Java中,可以使用:myComboBox.setOnChangeListener(...some code of listener interface...);)
您需要使用声明为WithEvents的组合框变量创建一个类模块.然后在创建组合框时,将其分配给类的变量.这样,您可以在设计时编写事件过程,但只有在创建组合框后才能进行监听.
创建一个名为CControlEvents的类模块
Private WithEvents mclsCbx As MSForms.ComboBox
Public Property Set Cbx(ByVal clsCbx As MSForms.ComboBox): Set mclsCbx = clsCbx: End Property
Public Property Get Cbx() As MSForms.ComboBox: Set Cbx = mclsCbx: End Property
Private Sub mclsCbx_Change()
MsgBox Me.Cbx.name
End Sub
Run Code Online (Sandbox Code Playgroud)
然后在标准模块中
'this is public so it doesn't go out of scope
Public gclsControlEvents As CControlEvents
Sub MakeCombo()
Dim oleCbx As OLEObject
'Create the combobox
Set oleCbx = Sheet1.OLEObjects.Add("Forms.ComboBox.1")
oleCbx.Object.AddItem "1"
oleCbx.Object.AddItem "2"
'hookup the events
Application.OnTime Now, "HookupEvents"
End Sub
Sub HookupEvents()
Set gclsControlEvents = New CControlEvents
Set gclsControlEvents.Cbx = Sheet1.OLEObjects(1).Object
End Sub
Run Code Online (Sandbox Code Playgroud)
现在,当组合框发生变化时,事件将会触发.
您必须使用与创建组合框不同的过程来连接组合框.有一个错误(或功能)阻止在同一过程中执行它.我认为与设计模式有关.这就是为什么在创建代码完成后使用Application.OnTime来运行连接代码的原因.
| 归档时间: |
|
| 查看次数: |
9823 次 |
| 最近记录: |