使用自定义类访问OLEObject事件 [英] Accessing OLEObject events using custom class
问题描述
我试图在Excel VBA中创建一个自定义类,以处理OLEObject(工作表上的ActiveX控件)的事件GotFocus和LostFocus.
I am trying to create a custom class in Excel VBA to handle the events GotFocus and LostFocus for an OLEObject (ActiveX Control on a worksheet).
自定义类 clsSheetControl
Dim WithEvents objOLEControl as OLEObject
Public Sub Init(oleControl as OLEObject)
Set objOLEControl = oleControl
End Sub
结束自定义课程
调用工作表
Public Sub SetControlHandler()
set clsControl = new ClsSheetControl
clsControl.Init(Me.OLEObjects("cmdControl1")
End Sub
结束工作表
当我在下拉列表中选择objOLEControl时,我能够在自定义类模块中创建"GotFocus"和"LostFocus",但是当行
When I select the objOLEControl in the dropdown, I am able to create "GotFocus" and "LostFocus" in the custom class module, however when the line
Set objOLEControl = oleControl
在自定义类中遇到,我得到了错误
is encountered in the custom class, I get the error
"459:对象或类不支持这组事件".
"459: Object or class does not support this set of events".
我尝试搜索答案,但是大多数结果都涉及访问OLEObject中的控制对象,而不是我在此处尝试做的事情.
I tried searching for the answer but most of the results deal with accessing the control object within the OLEObject, not what I am trying to do here.
编辑
这在工作表上也不起作用
This doesn't work on the worksheet either
工作表
Dim WithEvents objCtrl As OLEObject
Dim WithEvents chkCtrl As MSForms.CheckBox
Private Sub Worksheet_Activate()
Set chkCtrl = Me.OLEObjects("chkControl").Object
Set objCtrl = Me.OLEObjects("chkControl")
End Sub
Private Sub chkControl_GotFocus()
MsgBox ("chkControl has focus")
End Sub
行
Set objCtrl = Me.OLEObjects("chkControl")
引发相同的错误.但是,直接访问GotFocus事件(chkControl_GotFocus事件)是可以的.
raises the same error. However accessing the GotFocus event directly (the chkControl_GotFocus event) is fine.
推荐答案
这对我有用,但是它特定于Textbox控件,并且没有"GotFocus/LostFocus"事件...
This worked for me, but it's specific to Textbox controls and has no "GotFocus/LostFocus" events...
clsSheetControl
Dim WithEvents objOLEControl As MSForms.TextBox
Public Sub Init(oleControl As MSForms.TextBox)
Set objOLEControl = oleControl
End Sub
Private Sub objOLEControl_Change()
MsgBox "Changed"
End Sub
Private Sub objOLEControl_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
MsgBox "Key down: " & KeyCode
End Sub
工作表
Dim objControl As clsSheetControl
Public Sub SetControlHandler()
Set objControl = New clsSheetControl
objControl.Init Me.OLEObjects("TextBox1").Object
End Sub
这篇关于使用自定义类访问OLEObject事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!