Excel VBA – 获取button界面对象的相应范围

我怎样才能得到点击button的行?

大家好,我在这里需要一些帮助;)

我是VBA的新手我想在Excel中做一个button,但我很难找出如何找出点击button的行。 就像在照片中我想要的那样,当我点击“Sélectionnerun poste”button时,他会告诉我他的位置(我点击哪一行的button)

这里是我的代码来创buildbutton:

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 

这是我的事件button的代码:

 Sub PosteBtAction() AssocierSessoinCandidature.Show End Sub 

我有一个名为AssocierSessoinCandidature的应用程序窗口。 其实我想得到我点击的位置,并把这个信息发送到应用程序窗口。

这是我的示例Excel表单:

单击button时调用下面的Sub

 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 

我已经使用了非常相似的东西,你可以修改下面的代码:

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

点击button后,这段代码将把button24作为一个string的范围(不知道为什么我没有使用范围,你可以如果你愿意),并将其传递给函数CallAnotherFunction

总之,这是你所需要的:

 Shapes("button24").TopLeftCell.Address 

要么

 Shapes("button24").TopLeftCell.Row 

您可以访问TopLeftCellBottomRightCellButton对象的属性以获取绑定该控件的范围地址:

 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