我想使用以下类代码处理在类中单击 CommandButton 的操作
Option Explicit
Private m_First As MSForms.CommandButton
Private WithEvents evFirst As MSForms.CommandButton
Property Get First() As MSForms.CommandButton
Set First = m_First
End Property
Property Let First(ByRef o As MSForms.CommandButton)
Set m_First = o
Set evFirst = o
End Property
Private Sub evFirst_Click()
MsgBox "It Worked!"
End Sub
除了它不起作用之外,我想知道为什么表单中Button的引用与类中的引用不同,即:
Sub Tester()
Dim f As New UserForm1
Dim o As New cButtonClass
o.First = f.CommandButton1
Dim k1 As LongLong: k1 = ObjPtr(o.First)
Dim k2 As LongLong: k2 = ObjPtr(f.CommandButton1)
Debug.Assert k1 = k2 'NOPE!
End Sub
为什么这行不通?解决办法是什么?
答案 0 :(得分:2)
这里是更新的代码,反映了上述注释。它按预期工作。但是,对于您关于ObjPtr
的其他问题,我还没有答案。
这是课程代码:
Option Explicit
Private WithEvents evFirst As MSForms.CommandButton
Property Get First() As MSForms.CommandButton
Set First = evFirst
End Property
Property Set First(ByRef o As MSForms.CommandButton)
Set evFirst = o
End Property
Private Sub evFirst_Click()
MsgBox "Class Click"
End Sub
这是工作表代码:
Option Explicit
Public Sub Tester()
Dim f As UserForm1
Dim o As cButtonClass
Set f = New UserForm1
Set o = New cButtonClass
Set o.First = f.CommandButton1
f.Show vbModal
Dim k1 As LongPtr: k1 = ObjPtr(o.First)
Dim k2 As LongPtr: k2 = ObjPtr(f.CommandButton1)
Debug.Assert k1 = k2 'NOPE!
End Sub
这是用户表单代码:
Private Sub CommandButton1_Click()
MsgBox "UserForm Click"
End Sub