In the MyPolyAddress macro, Excel recorded references as absolute references in the A1
format (as opposed to the R1C1 format). As a result, the MyPolyAddress macro always
enters my name name in A2 and the address in A3, A4 and A5.
In VBA, cell selections are recorded as absolute references unless you click the Relative Reference
button on the Stop Recording toolbar. If you click this button, the recorder begins
recording relative references. If you click the button again, the recorder records subsequent
actions using absolute references—and so on. You can toggle between relative and absolute
references at any time while recording.
Tip: Check the Relative Reference button before you record
The Relative Reference button on the Stop Recording toolbar appears pressed in when
selected. This is your indication that the recorder is now using relative references. There is
no other indication, unfortunately. The button’s ScreenTip does not change to say Absolute
Reference. Because it’s important to know which mode you’re in when you record a macro,
it’s a good idea to check the appearance of the button before you start.
Suppose that instead of inserting my name and address in A2:A5 of the active worksheet,
you’d like to insert the address beginning at whatever cell happens to be active when you
run the macro. To do this, you need to create a new MyPolyAddress macro—we’ll call it
MyPolyAddressRel—that uses relative references instead of absolute references:
Sub MyPolyAddressRel() With Selection.Font .Name = "Arial" .FontStyle = "Bold Italic" .Size = 12 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone .ColorIndex = xlAutomatic End With ActiveCell.FormulaR1C1 = "Prof. Ming Leung" ActiveCell.Offset(1, 0).Range("A1").Select ActiveCell.FormulaR1C1 = "Polytechnic University" ActiveCell.Offset(1, 0).Range("A1").Select ActiveCell.FormulaR1C1 = "Six Metrotech Center" ActiveCell.Offset(1, 0).Range("A1").Select ActiveCell.FormulaR1C1 = "Brooklyn, NY 11201" ActiveCell.Offset(1, 0).Range("A1").Select End SubThe original macro enters my name and address in the range A2:A5, regardless of which cell is active when you start the macro. The new macro, on the other hand, enters the address starting in the active cell, no matter where that cell is located.
Range("A3").Selectwhereas the new version uses
ActiveCell.Offset(1,0).Range("A1").SelectTo move from the active cell to the cell below it in the new macro, VBA starts with the Active- Cell object, to which it applies the Offset method with two arguments for the number of rows and columns to offset. The Range keyword then returns a range with the same dimensions as its argument. In this case, the argument “A1” specifies that we want a range consisting of a single cell.