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

时间:2012-04-12 19:19:47

标签: 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);
}

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

2 个答案:

答案 0 :(得分:6)

您必须连接按钮事件。您可以在工作表激活事件处理程序中执行此操作:

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

答案 1 :(得分:0)

将Shapes.Name值重命名为您可以使用的值。

在Excel中创建一组形状时,可以说是矩形,右键单击第一个对象,然后转到“公式”选项卡并单击“定义名称”。在pup-up窗口的底部将是一行:引用[=“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"以获取特定于该按钮组的操作。

相关问题