2012-04-12 21 views
0

美好的一天。 我想找出發件人很多按鈕我們如何知道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,但它不起作用。任何樣品 - 建議?

+1

它是什麼類型的按鈕(forms?activex?)​​和它在哪裏(在表單上,​​在工作表上?)你嘗試了什麼VBA代碼?這可以起作用,但你需要提供更多關於你想要做什麼的細節...... – 2012-04-12 19:55:30

回答

4

你必須連接按鈕事件。您可以在工作表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 
0

重命名Shapes.Name值的東西,但是你可以使用你需要。

當您在Excel中創建一組形狀時,可以說矩形,右鍵單擊第一個對象,然後轉到公式選項卡並單擊「定義名稱」。在傀儡窗口的底部將是一行:引用[=「Rectangle 73」]這是您的VBA Shapes.Name值。 (在此處執行任何操作都不會更改VBA Shapes.Name值)

可以使用單個對象名稱與IF Application.Caller.Name = "Rectangle 73",或者可以將VBA中的形狀重命名爲更有用的東西。

如果您手動創建每個形狀,它們將是「矩形73」,「矩形74」,「矩形75」...如果您複製並粘貼,它們將是「矩形73」,「矩形102」 「Rectangle 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和Case "newName"的前7個字母,以獲取該按鈕組的特定操作。

相關問題