Avatar of FaheemAhmadGul
FaheemAhmadGul
Flag for United Kingdom of Great Britain and Northern Ireland

asked on 

VBA - how to make a Button refer to itself in its own click event in a generic way

I am wondering if there is a way a CommandButton on a VBA userForm can refer to itself in its own click event.
To clarify my question, I have a button named thisButton on my form. In its click event I would like to display a message box that will display its own caption in a message box. I can currently do this as I show in my code sample by saying thisButton.Caption but this means that if I want to do the same in the click event of another button named thatButton, then I have to say thatButton.Caption.
That is each button has to use its own name in the code to refer to itself.

In .NET applications the ClickEvent of every button has a parameter named sender that a button can use to refer to itself. I am wondering if such a thing is possible in VBA.
Thank you for your help.



Private Sub thisButton_Click()

MsgBox thisButton.Caption

End Sub

Private Sub thatButton_Click()

MsgBox thatButton.Caption

End Sub


' I would like to do this in the following way, if at all that kind of thing is possible

Private Sub thisButton_Click()
'' assuming sender here refers to the button that is being clicked
MsgBox sender.Caption

End Sub

Private Sub thatButton_Click()
' assuming sender here refers to the button that is being clicked
MsgBox sender.Caption

End Sub

Open in new window

VBA

Avatar of undefined
Last Comment
FaheemAhmadGul

8/22/2022 - Mon