excel - VBA按钮事件处理程序实现

标签 excel vba

我想使用以下类代码处理类中对 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

除了它不起作用之外,我想知道为什么表单中按钮的引用与类中的不同,即:

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

为什么这不起作用?解决方法是什么?

最佳答案

这是反射(reflect)上述评论的更新代码。它按预期工作。但是,对于您有关 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

关于excel - VBA按钮事件处理程序实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52747224/

相关文章:

php excel读取返回奇怪的字符

Java 对 Excel 的多个列表进行排序

ms-access - 如何在VBA IDE中使用 "Locals"窗口

excel - 将 2D 数组转换为 1D 数组

vba - 如何将 Excel 复选框(ActiveX 控件)链接到单元格?

arrays - 如何在 Excel VBA 中对数组进行切片?

excel - 使用 Excel::download() 方法将 Excel 列设置为自动

excel - 使用 VBA 在 Excel 中设置自动筛选

excel vba,从工作簿中删除所有名称而不循环

excel - 为行创建唯一序列