vba 使用自定义类访问 OLEObject 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10761973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing OLEObject events using custom class
提问by Bobsickle
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).
我正在尝试在 Excel VBA 中创建一个自定义类来处理 OLEObject(工作表上的 ActiveX 控件)的 GotFocus 和 LostFocus 事件。
custom class clsSheetControl
自定义类clsSheetControl
Dim WithEvents objOLEControl as OLEObject
Public Sub Init(oleControl as OLEObject)
Set objOLEControl = oleControl
End Sub
end custom class
结束自定义类
calling worksheet
调用工作表
Public Sub SetControlHandler()
set clsControl = new ClsSheetControl
clsControl.Init(Me.OLEObjects("cmdControl1")
End Sub
end worksheet
结束工作表
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
当我在下拉列表中选择 objOLEControl 时,我可以在自定义类模块中创建“GotFocus”和“LostFocus”,但是当行
Set objOLEControl = oleControl
is encountered in the custom class, I get the error
在自定义类中遇到,我收到错误
"459: Object or class does not support this set of events".
“459:对象或类不支持这组事件”。
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.
我尝试寻找答案,但大多数结果都涉及访问 OLEObject 中的控制对象,而不是我在这里尝试执行的操作。
EDIT
编辑
This doesn't work on the worksheet either
这也不适用于工作表
Worksheet
工作表
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
The line
线
Set objCtrl = Me.OLEObjects("chkControl")
raises the same error. However accessing the GotFocus event directly (the chkControl_GotFocus event) is fine.
引发同样的错误。然而,直接访问 GotFocus 事件(chkControl_GotFocus 事件)是没问题的。
回答by Tim Williams
This worked for me, but it's specific to Textbox controls and has no "GotFocus/LostFocus" events...
这对我有用,但它特定于文本框控件并且没有“GotFocus/LostFocus”事件......
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
Worksheet
工作表
Dim objControl As clsSheetControl
Public Sub SetControlHandler()
Set objControl = New clsSheetControl
objControl.Init Me.OLEObjects("TextBox1").Object
End Sub