0

我想找出许多按钮发件人

在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);
}

可以在 VBA (Visual Basic for Applications)中使用吗?我正在使用 Excel。我试过Application.Caller

4

2 回答 2

7

您必须连接按钮事件。您可以在 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

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

Public WithEvents cmdButton As MSForms.CommandButton

Private Sub cmdButton_Click()
 MsgBox cmdButton.Caption & " was pressed!"
End Sub
于 2012-04-12T20:07:37.923 回答
0

将您的 Shapes.Name 值重命名为您可以根据需要使用的名称。

当您在 Excel 中创建一组形状时,比如说矩形,右键单击第一个对象,然后转到“公式”选项卡并单击“定义名称”。在弹出窗口的底部会有一行: 指 [ ="Rectangle 73" ] 这是您的 VBA Shapes.Name 值。(在这里做任何事情都不会改变 VBA Shapes.Name 的值)

您可以使用单个对象名称,IF Application.Caller.Name = "Rectangle 73"也可以将 VBA 中的形状重命名为更有用的名称。

如果您手动创建每个形状,它们将是“矩形 73”、“矩形 74”、“矩形 75”……如果您复制并粘贴,它们将是“矩形 73”、“矩形 102”、“矩形 103” ... 现在我们有了 Shapes.Name 值,我们可以根据需要在 VBA 中重新定义它们。

Sub nameShapes()
    Dim shp As String
    Dim shpType As String
    Dim myName As String

'original root name of group shapes *do not include trailing space*
    shpType = "Rectangle"

'new name of group shapes
    myName = "newName"

'first number value of new shape names
    n = 1

'number values of first, second, and last shapes
    n1 = 73
    n2 = 103
    nx = 124

'active code --------------------------------------
'--------------------------------------------------
    shp = shpType & " " & n1
    ActiveSheet.Shapes(shp).Name = myName & " " & n

    For x = n2 To nx
        n = n + 1
        shp = shpType & " " & x
        ActiveSheet.Shapes(shp).Name = myName & " " & n
    Next n
'--------------------------------------------------
'active code --------------------------------------
End Sub

将此代码放在其自己的单独模块中,然后只需输入值并单击 RunSub 的 VBA 窗口工具栏中的播放按钮。

现在,您可以使用n = Right(Application.Caller, 2)来获取单击按钮的数值。一定要定义Dim n As Integer.

如果不同的按钮组调用相同的函数,您可以使用Select Case Left(Application.Caller, 7)获取 shape.name 的前 7 个字母以及Case "newName"特定于该按钮组的操作。

于 2013-10-05T17:55:46.663 回答