我们如何知道VBA中按钮的发送者?

ReP*_*PRO 0 events vba

美好的一天.我想找出发件人许多按钮.

C#中有类似的东西:

Button b = new Button();
b.Text = "Click 1";
b.Location = new Point(20, 20);
b.Size = new Size(100, 20);
// Our Handler
b.Click += new EventHandler(myClick);

// Implementation of next button...

// Add to form
this.Controls.Add(b);
this.Controls.Add(nextButton);
...

// And our event
private void myClick(object sender, System.EventArgs e)
{
   var mysender = ((Button)sender).Name;
   doAnything(mysender);
}
Run Code Online (Sandbox Code Playgroud)

我在VBA中没有任何想法(不是VB!).VBA表示Visual Basic for Applications.在VBA中有可能吗?我正在使用Excel.我已经尝试过Application.Caller,但它不起作用.任何样品 - 建议?

N0A*_*ias 6

你必须连接按钮事件.您可以在Worksheet Activate事件处理程序中执行此操作:

Dim arrEvents As Collection

Private Sub Worksheet_Activate()

Dim objButtonEvents As ButtonEvents
Dim shp As Shape

Set arrEvents = New Collection

For Each shpCursor In Me.Shapes
    If shpCursor.Type = msoOLEControlObject Then
        If TypeOf shpCursor.OLEFormat.Object.Object Is MSForms.CommandButton Then
            Set objButtonEvents = New ButtonEvents
            Set objButtonEvents.cmdButton = shpCursor.OLEFormat.Object.Object
            arrEvents.Add objButtonEvents
        End If
    End If
 Next

End Sub
Run Code Online (Sandbox Code Playgroud)

然后使用以下代码创建名为ButtonEvents的类模块:

Public WithEvents cmdButton As MSForms.CommandButton

Private Sub cmdButton_Click()
 MsgBox cmdButton.Caption & " was pressed!"
End Sub
Run Code Online (Sandbox Code Playgroud)