2016-08-30 20 views
2

如何獲取點擊按鈕的行?

大家好,我需要在這裏一些幫助;)Excel VBA - 獲取按鈕界面對象的相應範圍

我在VBA我試圖在Excel中的一個按鈕新手,但我難倒就如何找出點擊按鈕的排。像在照片上我想,當我點擊按鈕「Sélectionner聯合國郵政」然後他會告訴我他的位置(這是我點擊按鈕在哪一行)

這裏是我的代碼來創建按鈕:

Sub AjouterBoutonPoste(positionX As Integer, positionY As Integer, nom As String) 
    Set t = ActiveSheet.Range(Cells(positionX, positionY), Cells(positionX, positionY)) 
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height) 
    With btn 
    .OnAction = "PosteBtAction" 
    .Caption = "Sélectionner un poste" 
    .Name = nom & CStr(positionX) & CStr(positionY) 

    End With 
End Sub 

這裏是我的事件按鈕的代碼:

Sub PosteBtAction() 
    AssocierSessoinCandidature.Show 
End Sub 

我有一個應用程序窗口,它的名字是AssocierSessoinCandidature。其實我想獲得我點擊的位置並將這些信息發送到應用程序窗口。

這裏是我的榜樣Excel表:

回答

3

調用下面的子當按鈕被點擊

Sub foo() 

Dim obj As Object 
Dim row_no As Integer 

Set obj = ActiveSheet.Buttons(Application.Caller) 
With obj.TopLeftCell 
    row_no = .Row 
End With 
MsgBox "The Button is in the row number " & row_no 

End Sub 
0

我已經使用了非常相似的東西,你能適應下面的代碼:

Sub Button24_Click() 
Dim strShape As String 
strShape = Shapes("button24").TopLeftCell.Address 
CallAnotherFunction strShape 
End Sub 

在點擊按鈕,這個代碼將採取的範圍button24作爲一個字符串(不知道爲什麼我沒有使用範圍,你可以如果你願意)並將它傳遞給函數CallAnotherFunction

總之,這是你需要的:

Shapes("button24").TopLeftCell.Address 

Shapes("button24").TopLeftCell.Row 
0

可以訪問Button對象的屬性爲TopLeftCellBottomRightCell獲得地址的範圍約束控制:

Option Explicit 

Sub Test() 

    Dim ws As Worksheet 
    Dim btn As Object 
    Dim strAddressTopLeft As String 
    Dim strAddressBottomRight As String 
    Dim strButtonName As String 

    Set ws = ActiveSheet 

    For Each btn In ws.Buttons 
     strAddressTopLeft = btn.TopLeftCell.Address 
     strAddressBottomRight = btn.BottomRightCell.Address 
     strButtonName = btn.Name 
     Debug.Print "Range of button (" & strButtonName & "): " & _ 
      strAddressTopLeft & ":" & _ 
      strAddressBottomRight 
    Next btn 

End Sub