2
votes

I've recorded a simple macro that I need to make into something generic, so it can be used for any row and last four cells. Here is my recroded version:

Selection.End(xlToRight).Select
Selection.End(xlToRight).Select
Selection.End(xlToRight).Select
Selection.End(xlToRight).Select
Selection.End(xlToLeft).Select
Range("Q12:T12").Select
Range("T12").Activate
Selection.Copy

End Sub

How do I

  • make it go to the last cell of the ROW I place the cursor into?
  • change the cell specific ranges into a range that just means: select this cell and 3 more to the left?

... the selection.copy I think I can nearly manage :)

Many thanks Mike

2
PRO TIP: If you're using Excel for Windows, you can record your macros in RELATIVE mode instead of ABSOLUTE mode and get a recording in which all cell references are relevant to the starting selection instead of absolute.Joel Spolsky
Great tip, I'l make sure I use this next time. ThanksRocketGoal

2 Answers

5
votes

This will copy the last four cells in any row you click into:

Sub CopyLastFourCellsOfRow()
Dim lastCell As Range
Dim rngToCopy As Range

Set lastCell = Selection.End(xlToRight)
Set rngToCopy = Range(lastCell, lastCell.Offset(0, -3))

rngToCopy.Copy

End Sub

Update - If your row has broken data then best approach is to start in the final column of the spreadsheet (column IV) and then work back. To achieve this replace the lastCell statement with the following:

Set lastCell = Cells(Selection.Row, 256).End(xlToLeft)
4
votes

You can actually do the individual steps you're asking about all in one swift move. To make it go to the last cell in the current row, you just use ActiveCell.End(xlToRight). (Use 'ActiveCell' because it is equivalent to 'Selection' when only one cell is selected, but works even if multiple cells are selected.)

Range(ActiveCell, ActiveCell.Offset(0, -3)).Select

will select the current cell and 3 more to the left. Note that you do not need to do "Selection.Copy" in a separate step. You can simply go:

Range(ActiveCell, ActiveCell.Offset(0, -3)).Copy