Excel VBA: getting row of clicked button [duplicate]

筅森魡賤 提交于 2019-11-26 18:18:29

问题


This question already has an answer here:

  • Excel VBA - Get corresponding Range for Button interface object 3 answers

I am trying to make a button in Excel which copies a certain range of cells from the active workbook to another workbook. The copying of this range works perfectly when I specify a fixed range, but I am stumped on how to figure out the row of the clicked button.

Every row contains 7 or so cells, and the 8th cell contains a shape with a macro attached to it (the button). When the user presses this button the 7 cells on the same row as the row containing the pressed button need to be copied.

Using ActiveCell is of no use, since pressing the button doesn't actually set that cell as active. I searched around a lot but I can't seem to find how to obtain this value. Once I have the row number of the clicked button I can figure the rest out on my own.


回答1:


Each Shape has TopLeftCell property. It contains a cell within which the top left corner of the shape resides.




回答2:


There's a great solution mentioned here: http://www.ozgrid.com/forum/showthread.php?t=33351&p=167317#post167317

Golden code copied from the above post:

Sub Mainscoresheet() 
     ' Mainlineup Macro
    Dim b As Object, cs As Integer 
    Set b = ActiveSheet.Buttons(Application.Caller) 
    With b.TopLeftCell 
        cs = .Column 
    End With 
    MsgBox "Column Number " & cs 
End Sub 



回答3:


Excellent answer. Btw It also works for Rownumber!

'Same for rownumbers!
Sub Mainscoresheet() 
     ' Mainlineup Macro
    Dim b As Object, RowNumber As Integer 
    Set b = ActiveSheet.Buttons(Application.Caller) 
    With b.TopLeftCell 
        RowNumber = .Row
    End With 
    MsgBox "Row Number " & RowNumber 
End Sub



回答4:


This works too! Selects the cell that the generated button resides in (knew it was in column "K" but that could be calculated too!.

ActiveSheet.Range("K" & ActiveSheet.Buttons(Application.Caller).TopLeftCell.Row).Select


来源:https://stackoverflow.com/questions/6242605/excel-vba-getting-row-of-clicked-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!