12.2 Recording a Macro: Absolute vs Relative
Priya formats a packing header across nine columns every shift. The usual report begins at A1, but an extra report below another team’s notes starts at D5. Today you will record one version that always touches a fixed address and another that starts where you place the cursor. You will predict the affected cells before each replay.
A fixed address and a moving start cell
Use two blocks that look alike
Imagine a fictional seller handling orders from a storefront such as Amazon. These workbook values and procedures are training examples and do not describe Amazon's internal work. Priya has a small nine-column header for morning orders and a second header further down for an afternoon batch. She wants the formatting to be repeatable. She also wants to avoid placing a dark green header style on the first order row when somebody's cursor lands one row too low.
The Macro Recorder captures supported Excel actions and generates VBA. It can generate statements that select a range, set a font property or apply a fill. The recording stores the instructions for reproducing the action. It does not understand that a given row means “morning heading” or that an empty row means the packing list is finished. Treat the recorded code as a draft with a specific range and starting state.
- Fixed address: An instruction such as
Range("A1:I1").Selectrequests a particular cell address on the worksheet it refers to. Starting at D5 can still send it to A1. A bare Range call made in a standard module commonly uses the active worksheet, so the fixed coordinates themselves do not select a known sheet. - Relative address: An instruction that takes the active cell and builds a nine-cell range from it uses the active cell as the reference point. On A1 the destination is A1:I1. On D5 it is D5:L5. On D6 it is D6:L6, which may be the first data row. A flexible procedure still has a contract about its starting cell.
- Formatting: Changing the fill or font changes the display. The intended macro leaves order IDs, prices and formulas alone. When you test, calculate a total before and after and compare at least one adjacent cell. This gives you evidence beyond a neat appearance.
Track which parts depend on the current window
Excel's selection can hold a multi-cell block or an object. The active cell is one cell in the current worksheet selection. When you use the relative version in this lesson, select a single starting cell to make its meaning visible. In VBA, ActiveCell refers to the active window's worksheet cell. If the active window does not display a worksheet, the property can fail. Opening another workbook or clicking another tab changes the context for code that uses this property.
Relative references here describe what the recorder does with spreadsheet actions. The same vocabulary appears in a formula lesson when you copy a formula and Excel adjusts cell references. Dollar signs control row or column anchoring inside a formula. The Use Relative References switch controls how the recorder represents actions such as movement. If you record formula entry, read both the formula text and which cell receives it. One toggle cannot predict all the details of a captured automation.
Begin with a known state
- Use desktop Excel. The normal VBA recorder is in the Developer tools. Excel for the web cannot run VBA. Use a workbook you created, save it as a macro-enabled workbook and keep the existing trust policy in place.
- Set the recording mode before each test. Confirm whether Use Relative References appears active. Name the two recordings clearly and save them in the same practice file. Leave the shortcut box empty to make invocation explicit in the Macros dialog.
- Plan the actions on paper. Write the start address, the selection and the desired font state. Begin with a regular font so the change is visible. Press Stop Recording as soon as you finish the intended action. Reset your fixture manually after stopping.
- Try both starts. A recording made at A1 may look correct when replayed from A1, regardless of whether it uses a fixed or relative address. Test from D5 because it gives a distinct prediction. Then examine the adjacent cell after the nine-column span.
Remember: Fixed describes coordinates. Qualified describes which workbook or worksheet owns the coordinates. Relative describes the path from a stated starting position.
Read the geometry in a recording
One range, two number pairs
An offset is a move from a range. Its first number moves across rows, with a positive number moving down. Its second number moves across columns, with a positive number moving right. When an expression offsets a single cell, it returns another single-cell range. Resize instead changes how many rows and columns a range covers, keeping its upper-left cell as the start. A resize of one row by nine columns includes the first cell and the eight cells to its right.
ActiveCell.Offset(1, 2).Resize(2, 3)
ActiveCell.Resize(1, 9)
ActiveCell.Offset(1, 0).Select
- First expression from D5: Move down to row six and right from D to F. Size the result to two rows, six and seven, and three columns, F, G and H. The resulting range is F6:H7. The expression describes the range. A subsequent formatting command could change it without moving the cursor.
- Second expression from D5: Keep D5 as the left edge, include D itself and eight more columns, and keep a height of one row. The result is D5:L5. H5 lies within that block. M5 lies just beyond it and makes a good comparison cell.
- Third expression from D5: With positive one row and zero columns the result is D6. Calling Select changes the selection. If your recording contains this line after the styling, it may be there because you moved to the next row. A subsequent relative execution may now start at D6.
- Read the receiver: In some recordings you may encounter an expression such as
ActiveCell.Range("A1:I1"). Its left side is an existing Range, so the addresses inside that Range call refer to coordinates relative to it. The text A1:I1 can therefore appear in a relative recording. Inspect the complete expression before classifying it.
Read one change at a time
Find the procedure name. Find the first reference that picks a workbook, sheet or range. If the first meaningful statement is a bare Range call, the starting worksheet may still matter. If the code says ActiveCell or Selection, identify which prior statement set it. Then find the line where a property is assigned. A property is information about an Excel object, such as the font's bold setting. Assigning True sets Bold on. A second execution of that assignment targets the same state when the destination hasn't changed.
Recorder output can include detail from the chosen theme, decoration, blank movements and selections. The exact generated VBA depends on the Excel build and actions. Follow the order of the statements and ask what each one adds. A procedure can activate one tab, select a range, change its font and select another cell. If you run it a second time from that new cell, reproduce the starting state before using its output as evidence.
Set up two equivalent header blocks
Type the same columns at two addresses
| Order ID | Channel | Qty | Unit price | City | Promised min | Elapsed min | Status | Amount |
|---|---|---|---|---|---|---|---|---|
| NP-101 | Online | 2 | 45 | Pune | 12 | 11 | Delivered | 90 |
| NP-102 | Online | 3 | 35 | Nashik | 15 | 17 | Delivered | 105 |
Make a desktop workbook called RecordingPractice.xlsm with one worksheet called Practice and a second called Notes. Enter the header in A1:I1 and the first record in row two with its amount formula. Enter a second copy of the header in D5:L5 and the second record below it, with its own amount formula. Please use the calculations shown below rather than entering the two displayed amounts directly. Add “Keep this” in J1 and M5. Use them to check where a range ends. Place a sentence in A1 of Notes and confirm it survives the experiments.
I2: =C2*D2
L6: =F6*G6
- First layout: In the morning block C2 and D2 hold 2 and 45. I2 calculates 90. The ninth header is I1. A range with the right width includes it. J1 sits outside it.
- Second layout: In the afternoon block F6 and G6 hold 3 and 35. L6 calculates 105. The ninth header is L5. A range with the same width and a start of D5 includes it. M5 sits outside it.
- Use observable controls: The two data rows need to retain their formulas and amounts. The two extra markers remain unformatted. When a test says the first block is unchanged, look at A1, I1 and its amount rather than just glancing at the whole worksheet.
- Start in an ordinary range: Leave merged cells, tables and protected formatting out of this fixture. A direct formatting assignment and the recorder should now act only on the intended cells. A protected range may reject the command, and a merge can make the visible effect cover more than you expect.
Replay the same action from a second place
Choose the fixed address
Begin with both headers ordinary. The fixed instruction chooses A1:I1. It does so when you start from A1 or D5.
Reset the styles
Set the header fonts back to ordinary without editing any words or formulas. Place your cursor on the first cell of the second header, D5.
Choose the moving address
The relative instruction includes the start and eight more columns. D5 starts the span and L5 ends it. M5 is beyond the destination.
Read the boundary
Read the first and last header and the nearby marker in each range. Inspect I2 and L6. Expect 90 and 105 in both tests.
Lab one. Run a fixed-address recording twice
Record a visible change without a shortcut
- Save the practice workbook in a VBA-capable format. On the Practice tab, select a plain cell outside both headers, such as A4. Turn off Use Relative References. Start Record Macro as FormatHeader, choose This Workbook and leave the shortcut empty. This allows ordinary Excel shortcuts to retain their behavior.
- Select A1:I1 using the name box or drag across the exact cells, then set Bold. If you also choose dark green fill and white text as in the original packing demo, apply them consistently and note which properties need a manual reset. Stop recording before you move to another sheet or select your first test cell.
- In Developer Visual Basic, find the routine inside the workbook you created. Read how the recorded action addresses A1:I1 and whether worksheet references appear. Confirm that there are only formatting commands after the selection. Some Excel versions record several properties for a fill or a color change.
- Manually set both header ranges back to their original appearance. Select A1 and run the reviewed command from Developer Macros. Verify A1 and I1 are styled, J1 is ordinary, and the second header and both amounts remain as they were.
- Reset the header styles again and this time select D5. Run FormatHeader from the same Macros dialog. Expect it to choose A1:I1 on the active Practice sheet again. D5 and L5 should stay ordinary. If the result follows D5, inspect the exact generated address and the relative mode used when you recorded.
Option Explicit
Public Sub FormatHeaderDemo()
Range("A1:I1").Select
Selection.Font.Bold = True
End Sub
This is a short equivalent of the essential steps and helps you recognize the pattern when your recorder adds extra lines. The example uses a fixed address on the active worksheet, so run it only on Practice. The procedure first changes the Excel selection. The next statement applies the font setting to that selection. Replacing the first line with a different range can change the location while retaining the same formatting instruction.
Improve the destination after the first replay
Public Sub FormatPracticeHeader()
ThisWorkbook.Worksheets("Practice").Range("A1:I1").Font.Bold = True
End Sub
This version can be placed alongside the recorder-style example in the same standard module. Now the workbook and worksheet are explicit and you need no intermediate selection. To test the improvement, use Notes as the displayed tab and clear the style in Practice before returning to Notes. Run the named-sheet version, then read both worksheets. The recorded display change belongs to Practice. Notes has the same contents and style. Do not run the unqualified version on Notes just to prove it can format the wrong place.
Compare the evidence: A recording showing the A1:I1 address answers “which cells?” A line naming Practice in the code workbook answers “on which sheet?” The final font property answers “which change?” Use these three questions to explain your first fixed macro to someone else.
Lab two. Replay a movable nine-cell heading
Use the active cell as a deliberate input
- Make both Practice headers ordinary again. Select A1 before starting, confirm Use Relative References is on and record FormatHeaderFromStart in This Workbook. Keep the macro small enough to read without scrolling through several screens.
- Extend the current selection eight columns to the right while keeping its anchor at A1, for example by using Shift with the Right Arrow. Set the selected cells to Bold and then stop recording. Read the code. If the generated selection uses a fixed address, record the action again or use the exact written demo below. The experiment requires movement based on the current active cell.
- Reset the style in A1:I1 after stopping. Run the reviewed macro first from A1. Expect A1:I1 bold again. If the routine contains steps that move the selection, inspect where the visible cursor ends. Re-select the original start before repeating this run.
- Reset A1:I1 to ordinary. Select only D5. Run the relative routine. Expect D5:L5 bold, M5 unchanged and A1:I1 unchanged. Verify the formulas and outputs at I2 and L6. A successful demo follows the same geometric rule at the different starting position.
- Try the readable version below in a new standard module, or place it with the other demos after the module's existing Option Explicit declaration. Under the same conditions, run it from D5. This version checks the worksheet and available width before it can change formatting. It leaves the displayed selection alone, so a second run starts at the same cell unless the operator changes it.
Option Explicit
Public Sub FormatNineAtStart()
Dim ws As Worksheet
Dim startingCell As Range
Set ws = ThisWorkbook.Worksheets("Practice")
If TypeName(ActiveSheet) <> "Worksheet" Then
MsgBox "Select a cell on the Practice sheet."
Exit Sub
End If
Set startingCell = Application.ActiveCell
If Not (startingCell.Parent Is ws) Then
MsgBox "Select the first header cell on Practice."
Exit Sub
End If
If ws.Columns.Count - startingCell.Column + 1 < 9 Then
MsgBox "The header needs nine available columns."
Exit Sub
End If
startingCell.Resize(1, 9).Font.Bold = True
End Sub
- First check the active sheet type. An open workbook can show a chart sheet or a worksheet. If the active sheet does not contain worksheet cells, stop before requesting an active cell. This example expects its code workbook to contain Practice. A missing Practice sheet is a setup error to correct before running.
- Then compare the exact worksheet object. Another workbook might also contain a Practice sheet. Comparing the active cell's parent with the expected worksheet checks the particular object, including the workbook it belongs to. It also keeps the run away from Notes.
- Count available columns. If a sheet has sixteen thousand three hundred eighty-four columns and the active column is sixteen thousand three hundred seventy-six, there are nine columns including the active one. From the next column there are only eight. The subtraction plus one counts the first cell of the output rather than only its neighbors.
- Set one named effect. After the checks, resize the single active cell range and set Bold equal to True. This passes the same amount comparison as the recorder because it writes a font property. The procedure still relies on selecting a valid header. It could format a data row on Practice if you start on one, so the practice user's visual check remains part of the contract.
Challenge the starting cell without changing operational data
On a disposable practice file, select Notes and run FormatNineAtStart. It should ask you to select Practice and leave the Notes font alone. Next try a cell very close to the right edge. In a modern full-size worksheet, XEW1 leaves eight columns. The guard should stop before a nine-cell resize. An allowed start one column earlier, XEV1, leaves nine columns, although there is no reason to style those empty cells for this exercise. You can predict both results on paper before heading away from your sample.
On the Practice tab, predict what the relative procedure would do from D6. Its destination would be D6:L6, covering the order values instead of the labels in row five. To see the effect harmlessly, test this on a separate disposable copy and discard it afterwards. L6 would still calculate one hundred five but now have bold font. A formatting change without a value change can still confuse somebody reading the report. If you were adapting the practice routine for real use, you could check the first cell for the exact Order ID header text and stop when it is missing. Ask the report owner whether that text is stable before relying on it.
Read the recorder before adapting it
Explain four surprises using the current state
- Same run from two places: You chose D5, but A1:I1 changed. The code could use a fixed address. Open it and find the first range selection. Repeat with both headers ordinary and compare the two visible edges. Checking the cells directly is stronger than reasoning from where the cursor lands after the routine.
- Correct width, wrong sheet: Someone used the fixed example while another tab was active. An unqualified address can identify those coordinates on the active sheet. Restore the worksheet state from a backup or reset the practice copy manually. Use the qualified version to prove the intended write from Notes without touching the note.
- One step moves again on replay: A relative recording may move down after it formats. If you run the macro twice without resetting the cursor, it can style the next row on its second run. Read the last movement instruction. Either deliberately reposition before calling or remove an unnecessary movement from a separately tested written procedure.
- Range too large or too small: Dragging the mouse may have caught ten cells, or the action may have used an expanding shortcut. With A1 as the start, the ninth cell is I1, with J1 just beyond it. Check the generated range or resize count. Make the same comparison with L5 and M5 for the moved start.
Distinguish actions from transient display
Suppose somebody asks you to tell whether a recording actually ran. If the header was already bold, setting it to bold again can look exactly like no change. Start from an intentionally ordinary state. Confirm you opened the reviewed procedure and that Excel policy permits it. Keep two conditionally different fixtures: one in which both locations are ordinary and one in which only the first is ordinary. After each run, compare the exact first and last cells and the adjacent marker. When recording a toggle, read whether the generated VBA sets True, False or an expression; write down which starting condition makes its behavior observable.
Predict the new range first: Starting from D5, a two-row downward move and one-column rightward move lands at E7. Resizing that result to two rows by two columns covers E7:F8. Tell another student how you would check the formula and the adjacent visible styles after running a version that formats this range.
Choose a range boundary that will survive changes
Read a layout change before changing the macro
A fixed workbook template is easiest to maintain when its owners can tell which parts they are allowed to move. Suppose they add one column called Picker between Qty and Unit price in the first report. If the table header moves from nine to ten columns, an old nine-column procedure can format through Status and leave Amount ordinary. The formula may update its cell references when a column is inserted, so the amount can still be correct. That does not prove the report style covers the revised layout. Inspect the right edge and see which label is actually there.
A spreadsheet Table has a named header row whose shape belongs to the table. If the header's actual width should follow changes to a real Table, a later practice could resolve the named table and read its HeaderRowRange instead of counting nine cells. This removes the cursor dependency. It also requires the input to be deliberately created as the expected Table and assumes its headings are shown. Choose this only if the maintained layout is part of a Table. A nearby group of ordinary cells is a different structure even if it has a colored first row.
On this page you can use the clean nine-column fixture for both recordings and write a separate note about the ten-column variant. In that note identify the old right edge and the new Amount heading. Do not change the command to ten until you know whether the second block also gained a column. An automation taken from a recording rarely carries an explanation of what the layout means. Add a short description and one small verification table so the next person can extend the code from evidence.
Write a repeatable rule for the next person
Compare a report style with a placed stamp
Consider two people working from this practice workbook. Dan prints a report with its heading always at A1:I1. His routine knows the sheet, the header text and its width. A direct qualified range is easy to explain and rarely needs manual positioning. If he moves the report under a logo and changes to A3:I3, he needs to change the address in the routine or use a stable workbook name referring to the header. Replaying the old recording at A3 with the fixed address would still change A1. Dan's workbook contract is tied to its layout.
Priya applies the same visual stamp to a block selected by the person preparing the report. She may have two batches stacked vertically or separate headings farther down the sheet. In her case the user says where the stamp starts, and the formatting has the same dimensions. The interface should label a button or command so it reminds the operator to select a header first. This makes the selected start an input to the command just as quantity is input to a formula. Unlike a folder compiled from past reports, the user's current selection can change between runs, so the use instruction matters.
- Write the fixed rule: “From any displayed tab, make the nine cells A1 through I1 on our Practice worksheet bold.” This takes a workbook and sheet as explicit objects. It does not ask which cell is currently selected. The person running it can prove the Notes worksheet survives.
- Write the moving rule: “On Practice, select the first header cell and make that cell and the next eight cells in the same row bold.” This depends on the active cell, checks the intended worksheet and describes when the result moves. A known header line lets the reader validate both left and right edges.
- Write the boundary rule: “If the start has fewer than nine columns available, end without applying any style.” For the standard modern grid, XEW leaves eight and XEV leaves nine. Confirm under the actual worksheet's column count. Data values and the adjacent marker should survive even after a rejected call.
- Write a validation step for a real handoff: “After the run, compare the right-most header and the next cell. Your expected label is Amount and the marker beyond it is unchanged. Check the first formula below the header before releasing the report.” This tests the outcome and the action's blast radius in the same place.
Try an edited layout on paper first
Imagine a third tiny block near B9. The nine labels would live from B9 through J9, and K9 would be your next-cell marker. Its quantity and price live in D10 and E10. If you choose D10 as the start, the formatting would go from D10 through L10, styling the data row and reaching farther right than the block you meant. Write both destinations and circle the part the routine would cover unexpectedly. This example lets you identify a bad starting choice even when all numeric amounts are still correct.
One partner can pretend to manage the template while another plays the person replaying the macro. The template owner marks the expected start and finish of each block. The operator traces the generated range from a deliberately chosen cursor position without being told whether the code is absolute or relative. Then switch roles and determine which part of the routine must change for each new layout. A useful answer includes the cell addresses, which workbook and worksheet they belong to, and whether the choice remains stable when the user moves to another tab.
Choose a useful test: Ask a colleague to start from a different valid header. If your instructions do not say whether the second header or the original one should change, settle that question before adding a button or shortcut.
Quick checks
Predict each exact destination
You selected D5. What does a fixed address A1:I1 change?
It formats the nine cells from A1 to I1 on the worksheet it refers to. In a bare Range call from the standard module, that may be the active worksheet. If the call begins with ThisWorkbook and Practice, the explicit worksheet decides which A1:I1 is touched. The cursor position does not move the address.
Which cell is just beyond a nine-column relative range starting at D5?
M5 is just beyond it. Count D as one and L as nine, keeping the row at five. A check that tests D5, L5 and M5 catches an eight-column mistake and a ten-column mistake. Looking only at D5 could give the same answer in all three cases.
What range is returned by the offset and resize from D5?
Offset by one row and two columns lands at F6. Resize to two rows by three columns covers F6:H7. The destination is a Range object. It changes a cell or the current selection only when the next instruction tells Excel to apply an effect or select it.
Does ActiveCell.Range("A1:I1") always refer to the sheet's first row?
Its receiver is the active cell as a Range, so the coordinates are interpreted relative to it. The same A1:I1 text under a worksheet receiver would identify the sheet's first nine columns on row one. Read the words to the left of Range before assuming where it starts.
Does running the nine-cell style change the two totals?
Neither of the reviewed demonstrations should alter the formulas or input. I2 remains 90 and L6 remains 105. A separate quantity change or a hidden write recorded by accident would change that result. Read the formula bar and perform the independent multiplication as you compare.
Why may a second run with the same macro format a different row?
The first run may have changed which cell was active. If a final recorded move goes down one row, the next invocation has a different starting point. Restore the starting selection between tests or remove the unneeded movement once you understand the code and can test its exact replacement.
Interview and discussion
Explain your reasoning to somebody who maintains the workbook
When would you prefer the absolute recording?
Use fixed coordinates when a maintained report has one stable header location that should be styled regardless of the operator's cursor. Also qualify its worksheet if it should work from different tabs. Add a check after template edits to confirm the header still occupies the coordinates you planned.
When would you choose a relative recording?
Let a person choose the starting cell when different reports have the same shape in different places. Write down what a valid start looks like and the number of cells that will be affected. Check an alternate start and one cell outside the affected area. If users choose the wrong start too often, consider a named or validated destination.
How do you turn a recorder's actions into a direct formatting procedure?
Read the generated range selection and the following property assignment. Make the object owning the range explicit, then assign the desired property on that range. In this example a worksheet reference followed by A1:I1 and Font.Bold accomplishes the same desired effect without switching the selected cells. Confirm the intended appearance and preserved formulas on a clean copy.
What does a workbook boundary check contribute to a relative macro?
It can reject another worksheet with the same name if it is a different object. In FormatNineAtStart the starting cell's parent must be the same Practice object as the one in the code workbook. After the check the chosen worksheet is known, while the current operator still chooses which of its header starts to use.
How would you test the right boundary from a modern worksheet?
Count the starting column as one available cell. With the last column at 16384, starting at 16376 gives nine cells through the last column. Starting at 16377 gives only eight and should exit before a resize. Read the guard first and write down both expected results so you know whether the actual behavior is correct.
Six recall cards
- Fixed coordinates
Range A1:I1 has the same coordinates when the cursor moves. Identify the owning sheet to remove ambiguity about the destination.
- Moving position
The relative version starts at the active cell. Start at D5 to write the nine-column style from D5 through L5.
- Two number pairs
Offset shifts the start by rows and columns. Resize changes the number of rows and columns covered.
- Check the edge
From A1 the ninth cell is I1 and the next is J1. From D5 use L5 and M5. Read both edge cells after the run.
- Recorder movement
Select can make your second run start somewhere else. Inspect the final selection step before repeating a movable procedure.
- Control cells
Formatting should leave 90 and 105 in the amount formulas and leave the unrelated Notes sheet intact when you use the guarded example.
Microsoft references
Continue practising: explore the existing Excel Task Hub for additional exercises.