excel 使用自定义类访问OLEObject事件

k0pti3hp  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(130)

我正在尝试在Excel VBA中创建一个自定义类,以处理OLEObject(工作表上的ActiveX控件)的GotFocus和LostFocus事件。
自定义类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”,但是当行

Set objOLEControl = oleControl

在自定义类中遇到,我得到错误
459:对象或类不支持此事件集。
我试着搜索答案,但大多数结果都涉及访问OLEObject中的控件对象,而不是我在这里要做的。

编辑

这在工作表上也不起作用

工作表

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事件)就可以了。

kknvjkwl

kknvjkwl1#

这对我很有效,但它是特定于文本框控件的,没有“GotFocus/LostFocus”事件...

类工作表控件

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

相关问题