Common event handler to get the name of ActiveX bu

2019-08-11 11:41发布

So I was wondering if I can reference the button that was clicked. So I do not have to change the code to much for every button. So here is what I have.

Private Sub CommandButton1_Click()

Dim name As String
With CommandButton1

If .Caption = "CommandButton1" & "" Then
name = InputBox("Enter Template Name.")
.Caption = name

End If
End With

End Sub

Instead of With CommandButton1 I want it to use the button that was clicked. I tried With Me but it did nothing.

1条回答
smile是对你的礼貌
2楼-- · 2019-08-11 11:51

The answer in this SO post solves your issue.

Follow the instructions carefully. It should solve your problem. :)

EDIT:

It's pretty easy, actually.

SCREENSHOTS:

Set-up of my sheet:

enter image description here

Set-up of the VBE, Sheet1's code:

enter image description here

NOTE THE HIGHLIGHTED PARTS!

Set-up of the VBE, Class Module:

Add a class module by inserting Class Module rather than just Module. The name should exactly be ButtonEvents.

enter image description here

Result when CommandButton1 is clicked:

enter image description here

===============

This is just the basic premise, of course. Instead of showing a message box, you can instead change the code in the class module to have the name stored somewhere or send it to a particular cell, etc.

Hope this makes it clearer.

查看更多
登录 后发表回答