Moving to a Different Cell in an Excel Macro, Relatively Speaking

Excel IconPrimarily a note to myself, but…

… in Microsoft Excel, the Macro Recorder defaults to storing an absolute cell address when recording a macro.  I seem to typically want a relative address, such as “three cells to the left.”  I can never remember the Visual Basic Syntax for moving the cursor relative to the current cell so I’m writing it down here.

The Visual Basic property is Offset and some sample code is:

Sub SetStations()
'
' SetStations Macro
' Macro recorded  by thomas brightbill
'
' Keyboard Shortcut: Ctrl+t
'
' This cell is 1.5 LESS than the cell 18 columns to the left
   ActiveCell.FormulaR1C1 = "=+RC[-18]-1.5"
' Move right one cell
    ActiveCell.Offset(0, 1).Select
' This cell is 1.5 MORE than the cell 19 columns to the left
    ActiveCell.FormulaR1C1 = "=+RC[-19]+1.5"
' Move right one cell
    ActiveCell.Offset(0, 1).Select
' Enter the Text String 'Other' in this cell
    ActiveCell.FormulaR1C1 = "Other"
    ActiveCell.Offset(0, 2).Select
    ActiveCell.FormulaR1C1 = "Steel"
    ActiveCell.Offset(1, -4).Select
End Sub

Links to Microsoft Knowledgebase:

http://support.microsoft.com/kb/291308

This entry was posted in Technology and tagged , , . Bookmark the permalink.