Home » excel » excel – VBA button event handler implementation

excel – VBA button event handler implementation

Posted by: admin April 23, 2020 Leave a comment

Questions:

I want to handle the click on an CommandButton from within a class using the following class code

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

In addition to it not working, am wondering why the reference for the Button in the form is different from that in the class, ie:

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

Why doesn’t this work? What is the fix?

How to&Answers:

Here is updated code reflecting the above comments. It works as expected. However, I don’t have an answer yet for your other question concerning ObjPtr.

Here’s the class code:

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

Here’s the sheet code:

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

Here’s the userform code:

Private Sub CommandButton1_Click()
   MsgBox "UserForm Click"
End Sub