Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA: getting row of clicked button [duplicate]

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.

like image 686
Jort Avatar asked Jun 05 '11 11:06

Jort


3 Answers

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

like image 195
GSerg Avatar answered Nov 08 '22 08:11

GSerg


Try this:

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 
like image 30
FraggaMuffin Avatar answered Nov 08 '22 06:11

FraggaMuffin


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
like image 8
Robert Nagtegaal Avatar answered Nov 08 '22 06:11

Robert Nagtegaal