12.7 Range, Cells and Worksheets
Vikram has two workbooks open. Both have a tab called Orders. He wants a new calculation on one tab in one file. The formula is simple, but a bare cell reference can point to the other workbook. This lesson shows how VBA chooses a workbook, worksheet and cell range, then uses that path to write a formula or copy a small rectangle deliberately.
Follow the address all the way to the cell
Use one exact workbook and one exact worksheet
A fictional Blinkit-style reporting team needs an amount column to review before publishing a handoff. The figures and reporting actions are invented for practice. The analyst will multiply each original amount by a fixed 1.05 demonstration factor. The change belongs in a new column to the right of the source. It needs to happen even if a second workbook called Orders Copy is in front. Naming the workbook and worksheet in VBA removes the need to coordinate where a person's screen is pointing.
- Workbook: One Excel file open in the current desktop application.
ThisWorkbookidentifies the workbook holding the running VBA.ActiveWorkbookrefers to the workbook in the active window when available. Those can be different after an analyst clicks another workbook. - Worksheet: The worksheet comes from a collection of worksheets in a named workbook. Use
ThisWorkbook.Worksheets("Orders")in this lab. A tab name can exist in several files. The worksheet variable points to the specific object you resolved. - Range: A Range object can refer to one cell or a larger part of a worksheet. For example
ws.Range("J2:J11")names a single-column rectangle. The object supports reading values, writing a value or formula, applying a number format and many other actions. - Cell coordinates:
ws.Cells(2, 3)means row two, column three on that entire worksheet, which is C2. Row and column indices here start at one. Use a text address when the location is fixed and easy to see. Use row and column numbers when you compute endpoints from known data.
Decide whether the code owns the workbook it edits
Today the code lives in the file it must edit: RangePractice.xlsm. A routine in this workbook can use ThisWorkbook to avoid accidental writes elsewhere. Later, a personal macro or add-in may intentionally edit another workbook. In that case decide which actual target you are allowed to edit and validate it explicitly. A workbook in front might not be the file the person meant to prepare. If a name or selection is used as input, reject a missing or unexpected target before writing.
Look at the receiver, the expression before the dot. A bare Range or Cells reference in an ordinary standard module often uses the active sheet. A Range belongs to a worksheet in an explicit expression such as ws.Range("A1"). An expression can also call Cells on an existing Range, where row and column positions are relative to its first area. In this lesson, use the entire worksheet object when expressing absolute grid coordinates.
Remember: The name Orders is useful after you know which workbook owns it. Give both endpoints and every cell read the same worksheet qualifier.
Read, write and reshape a range deliberately
Separate locating a range from taking an action on it
| Expression | Meaning | Evidence |
|---|---|---|
ws.Range("G2") | Cell G2 | One worksheet property receiver |
ws.Cells(2, 7) | Row 2, column 7 | The same G2 address |
ws.Range("A1").Offset(1, 2) | Move one row down and two columns right | C2 |
ws.Range("A1").Resize(5, 3) | Keep the start and size to five by three | A1:C5 |
ws.Range("J2").Formula | Formula of J2 | Read it or set a string containing a formula |
ws.Range("J2").Value2 | Current calculated or stored value | Read 67.2 after calculation |
- Build a rectangle from two cells.
ws.Range(ws.Cells(2, 10), ws.Cells(11, 10))makes the one-column block from J2 to J11. Both Cells calls belong to ws. If the second call were unqualified, Excel could supply a cell from another worksheet, which cannot be combined into the same rectangular range. - Set a value. Assigning a literal to a cell's Value2 writes data. If the cell previously contained a formula, replacing its value also replaces the formula. Treat an output area as a clear contract so you know it is fine to replace what exists there.
- Set a formula. Assigning a formula creates a dependency on the other worksheet data. Editing a source value can change a formula result when the workbook calculates. Writing the current result into another range via Value2 gives the recipient a snapshot.
- Clear contents deliberately. ClearContents removes values and formulas in its addressed range and retains formatting. We will use it only on a reserved scratch area while testing a copy. Clearing an entire column because it contains an output cell could also remove unrelated inputs.
- Find a connected block. CurrentRegion gives a surrounding region bounded by blank rows and columns. It is useful for a contiguous little table with known surroundings. A blank dividing row or connected nearby labels can change the boundary. Verify its address and dimensions before using it for an edit.
Distinguish moving the address from moving the cursor
Offset returns a Range and Resize returns a Range. Neither needs to change the selected cell to create that reference. If code later calls Select, it changes the visible selection and introduces a dependency on the worksheet displayed at that point. A direct assignment to a qualified range can write independently of the current view. Use explicit activation only when the user needs to look at a particular sheet, and keep it separate from how data is chosen.
Adding a new worksheet is also an action on a specific workbook. A worksheet reference can be stored immediately when it is created, rather than assuming the new one is always the sheet active on screen. A named worksheet within a workbook must have a distinct tab name. The labs on this page create their worksheets manually so that the output code needs to write only the declared ranges.
Lab one. Write ten formulas without selecting a cell
Set up the inputs where the code will read them
Make your own macro-enabled workbook called RangePractice.xlsm and a worksheet called Orders. The source is the ten orders from the formulas chapter. In the small version use the IDs in A2:A11 and the amounts in G2:G11. Enter the headers Order ID in A1 and Amount in G1. If you already copied the full course table, those positions already belong to those fields. Keep J1:J11 available for the calculation. Put a date, label or note in K1 that you will check after the run. In a separate Notes sheet keep an independent marker.
| Row | Order ID | G amount | Expected J |
|---|---|---|---|
| 2 | BLK-1001 | 64 | 67.20 |
| 3 | BLK-1002 | 270 | 283.50 |
| 4 | AMN-1003 | 110 | 115.50 |
| 5 | BLK-1004 | 240 | 252.00 |
| 6 | AMN-1005 | 232 | 243.60 |
| 7 | BLK-1006 | 150 | 157.50 |
| 8 | BLK-1007 | 1299 | 1363.95 |
| 9 | AMN-1008 | 195 | 204.75 |
| 10 | BLK-1009 | 220 | 231.00 |
| 11 | BLK-1010 | 90 | 94.50 |
Use 5% solely as a fixed practice factor. Actual tax or fee rules can depend on the product and business context. A useful source for this lesson is simply “increase each exercise amount by five percent.” We will use an R1C1 formula to express “same row, three columns left” from every destination cell. This is explicit even when the same formula string is assigned to a whole rectangle.
Option Explicit
Public Sub BuildPracticeAmountColumn()
Dim ws As Worksheet
Dim output As Range
Set ws = ThisWorkbook.Worksheets("Orders")
Set output = ws.Range(ws.Cells(2, 10), ws.Cells(11, 10))
ws.Range("J1").Value2 = "Practice amount at 105%"
output.FormulaR1C1 = "=RC[-3]*1.05"
output.NumberFormat = "#,##0.00"
End Sub
Read the formula from its own cell
People often read worksheet addresses as a column letter and a row number. That is called A1-style notation. R1C1-style notation organizes the row and column parts as R and C. Within this example R by itself refers to the current row, while C followed by minus three in square brackets refers to the cell three columns to the left. In J2, that points to G2. In J11, it points to G11. The same relative expression performs the intended calculation from each destination row. The number format changes the display of the result without changing the formula.
- One cell proof: J2's source is G2, which contains 64. Multiply by 1.05 to get 67.20. This is also what writing an explicit A1-style formula for that single cell would do.
- Two cells proof: J3 uses 270 in G3, and J11 uses 90 in G11. The formulas are not pulling 64 for every result. Read the formula bar and calculate a bottom-row value to catch this mistake.
- Full-column proof: The ten G values sum to 2,870. Applying the same fixed factor gives 3,013.50 across the ten J values. An independent check can multiply the original sum without relying on your inserted formulas.
Replay from another tab and compare the workbook data
- Enter the module in the code project for RangePractice. Make sure the actual Orders worksheet is named exactly. Select Notes and run BuildPracticeAmountColumn through the Macros dialog focused on This Workbook. The displayed selection and notes should stay put.
- Read the two outer J formulas and their results separately. If your formula bar uses standard A1-style addresses, expect formulas referring to G2 and G11 on the appropriate rows. If it uses R1C1-style settings, use the corresponding relative positions. Confirm the two edge amounts and preserve your note in K1.
- In unused cells write the two independent checks below. They should give the same number for the complete fixture. After reading both, change G2 from 64 to 80. J2 rises from 67.20 to 84 and the overall result becomes 3,030.30 once calculated. You do not have to rerun the macro for the installed formula to respond.
- Restore the original 64 and verify that the numbers return to their previous state. Rerun the macro deliberately. It replaces the ten formulas in the same reserved cells, so it does not add a second output column. Never run an output write blindly when another report already owns that range.
=SUM(G2:G11)*1.05
=SUM(J2:J11)
Trace the range from coordinates to live formulas
Name the owner
Use the workbook holding the macro and retrieve its Orders sheet. The Notes tab may still be in front.
Build both endpoints
Row 2 column 10 gives J2. Row 11 column 10 gives J11. Both point to the same sheet.
Write one relative rule
Each destination references its own row, three columns to the left. J2 points to G2 and J11 to G11.
Verify the remaining data
Both sums match the factor check. Changing one original amount updates its formula result while the note and other rows remain intact.
Lab two. Take an exact three-row snapshot without copying the layout
Set up a contiguous source and a separately sized destination
Add a tab called LookupPractice. Put the headers Key and Amount in C1 and D1. Enter three records starting in C2. Use an amount formula in D2 so you can see the difference between keeping a formula and copying its current value. Keep column B, column E and row five blank around this block. That leaves enough empty border for the CurrentRegion comparison later in the lab. On a different worksheet called Review, reserve F3:G5 for output and add separate headers at F2 and G2.
| Cell row | Key | Amount |
|---|---|---|
| 2 | QP-701 | 71 |
| 3 | QP-702 | 120 |
| 4 | QP-703 | 45 |
For D2 write the simple formula below and read 71 on the worksheet. Use ordinary numbers for D3 and D4. On Review format G3:G5 with two decimal places and put a marker in H3. Add the second formula in an unused cell on Review, for example H5, to check the current snapshot. Read the result only after the copy. It should be 236. A source data read uses two dimensions because the source has three rows and two columns.
LookupPractice D2: =70+1
Review H5: =SUM(G3:G5)
Public Sub CopyPracticeSnapshot()
Dim source As Worksheet
Dim destination As Worksheet
Dim records As Range
Dim target As Range
Dim entries As Variant
Set source = ThisWorkbook.Worksheets("LookupPractice")
Set destination = ThisWorkbook.Worksheets("Review")
Set records = source.Range("C2:D4")
entries = records.Value2
Set target = destination.Range("F3").Resize(records.Rows.Count, records.Columns.Count)
target.Value2 = entries
End Sub
Put the second procedure below the first in the same module. It reads the three-by-two source block into one Variant variable. The result is a two-dimensional array, a set of values arranged in rows and columns. Each row of the array contains a key and amount next to each other. The destination is built from the two source dimensions. Giving both sides the same shape avoids a missing element or a shifted amount. A single-cell range read can instead return a single value, so specify the shape before reusing this example on variable input.
Verify shape, values and the two important differences
- Run CopyPracticeSnapshot in the practice workbook. Examine Review F3:G5. The three key-and-value pairs should stay in row order. F3 shows QP-701 and G3 shows 71. F5 shows QP-703 and G5 shows 45. H5 should calculate 236. H3 should retain its marker.
- Inspect the formula bar for LookupPractice D2 and Review G3. The first should contain the formula for 71. The second should contain 71 as a stored value with no calculation. The destination number format can present that value as 71.00. This operation places values rather than reusing the source formatting or formulas.
- Change LookupPractice D2's formula in the practice copy to 80 plus 1. Its new source value is 81. Review G3 holds 71 until a new snapshot is taken. Run CopyPracticeSnapshot to update G3 and check the new total 246. Restore the original source formula and run again to recover 236.
- Try a read-only address check from the Immediate window. The exact expression below returns the connected block around C2 in the open workbook. The blank edges yield C1:D4, which includes the header. An annotated note next to the table could change that block. Our explicitly chosen C2:D4 skips the header and does not depend on surrounding notes.
- In this disposable workbook you can reset only Review F3:G5 using Clear Contents from the worksheet or an equivalent qualified statement. The two-decimal formatting and Review headers and note remain. H5 becomes zero with no snapshot amounts. Run CopyPracticeSnapshot after restoring 71, 120 and 45. Then verify the formatted entries are back and H5 again shows 236.
? Workbooks("RangePractice.xlsm").Worksheets("LookupPractice").Range("C2").CurrentRegion.Address
Expected output from the address check: The worksheet normally reports the absolute address $C$1:$D$4 for the connected region. The formula output was built from a different range without headers. Using the connected region as a source would change the height and move the intended output rows. State the intended rectangle before deciding which property to use.
Diagnose a wrong range with a second example
Use the shape and owner to distinguish a bug
- Wrong workbook: A named tab can exist in both open files. Verify that the code's project lives in RangePractice and that it uses ThisWorkbook for the qualified destination. In a different context, validate the actual chosen workbook before editing. Use a distinct control note in each copy so you can see precisely which file answered your request.
- Wrong row: Check both endpoint cells, including their row numbers. A copied snapshot beginning at C1 includes headers, so the first destination row would hold text instead of the first key and price. A formula intended to cover J2 to J11 may omit the last source if its ending row is ten. Always check at least one identified bottom record.
- Wrong column: Read the column number on a Cells call and compare with the text address. J is ten and G is seven. R1C1 uses a difference of minus three here. A minus two expression would point to H instead. In a full lesson workbook H contains minutes and calculation values may still look plausible. A known first amount gives a better test than checking only that the formula returns a number.
- Unexpected cleared label: Check the exact dimensions of ClearContents in a disposable copy. The lab owns F3:G5. Its headers are at F2:G2. Clearing one additional row upward would remove those headers. If the amount has gone but its two-decimal format is retained, that is consistent with ClearContents rather than changing all formatting.
- Wrong formula after bulk write: Inspect the first, second and last destinations from their own formula bars. A1-style reference text and formula assignment behavior can be confusing when applied across a rectangle. This lab uses an explicit row-relative R1C1 expression for every target. If you use an A1-style top-cell formula and FillDown instead, check that the copied top formatting is also acceptable.
Predict a separate layout before making it
Imagine the source for the charged amount moves from G to H after insertion of an extra field and the destination stays J. The old same-row minus-three rule still points to G. The new relative difference from J to H is minus two. Which location changes depends on the intended worksheet design, not simply the open tab. Before deploying a modified formula, ask the template maintainer for the input column meaning, verify its header and test one known first and last row. The location change should be explicit in the documentation of the routine.
Likewise, if the snapshot source gets a fourth record, extending C2:D4 to C2:D5 would produce a four-by-two rectangle. The target resized from F3 would be F3:G6. That assumes the destination owns the extra row. If Review G6 contains a different report, the routine needs a new boundary or a rejection rule. Geometry can be correctly computed and still target cells the task does not own. Decide scope with the report owner before making a larger reusable procedure.
Explain the distinction: The formula column stays tied to the current source amounts. The snapshot stores the values seen at the last copy. An independent calculation beside each can reveal which one is current after a source edit.
Check the receiver before using two endpoints
Compare workbook-relative, worksheet-relative and range-relative references
The object model gives you access to the same grid through different receivers. That is useful when the range is already known. It also creates mistakes that look reasonable when read quickly. Imagine you are tracing a cell in the upper-left part of a template. Your teammate calls ws.Cells with row two and column three and expects C2. That is correct when ws is a worksheet. Now they first choose a range D5:F7, then call Cells with the same arguments. The start of that range is D5. From that start, relative row two is row six and relative column three is F. The result for the second expression is F6.
ws.Cells(2, 3)
ws.Range("D5:F7").Cells(2, 3)
ws.Range("D5:F7").Offset(1, 2)
ws.Range("D5:F7").Resize(2, 1)
- Entire worksheet receiver: The first expression starts from the worksheet's row one and column one, so it points to C2. Use this when the numbers you computed describe absolute grid coordinates.
- Existing rectangle receiver: The second expression first locates D5:F7 and indexes cells relative to that range. This can be convenient if you are reading inside a small known block. Check the row and column numbers against the block's intended dimensions rather than expecting this expression to enforce its boundaries.
- Offset already knows the rectangle: The third expression shifts the whole three-by-three range down one row and right two columns. The top-left cell becomes F6 and the bottom-right becomes H8. The dimensions stay three by three. Applying Offset to one cell instead would return just the moved cell.
- Resize keeps its starting position: The fourth expression keeps D5 as its upper-left cell and uses a height of two and width of one. The result is D5:D6. Its third row and remaining columns from the earlier shape are outside the new reference.
Read a With block as a way of naming the receiver once
VBA also lets you group several statements applying to one object under With ws. A leading dot inside that structure tells VBA to use the With object for the call. In the example both Cells calls need their leading dots as well as Range. One missing dot would change the receiver for that endpoint. Format the declaration to make that visible as you review. This example belongs inside a procedure after setting ws.
With ws
Set output = .Range(.Cells(2, 10), .Cells(11, 10))
End With
Read that statement before changing it to a new source. You can describe both endpoint objects and their parents. A three-dimensional range spanning two worksheet objects is not the block described by the lab. If you want to address two worksheets, compute and test the two ranges separately. The named destination sheets in the snapshot lab behave independently in this way.
Trace the shape of an array across worksheets
For the snapshot, read the dimensions of C2:D4 as three rows and two columns. The first row consists of QP-701 and 71. That row becomes the corresponding first row in F3:G5. The second row becomes QP-702 and 120, and the third becomes QP-703 and 45. Nothing about appending the range object to another workbook tells Excel to sort or transpose the values. The exact output shape is a decision made in the Resize call.
Suppose you accidentally size the destination with columns first, choosing two rows by three columns. That gives F3:H4, which touches H3, the reserved note. The total of target cells is still six, just as it was for the three-by-two source. Matching total cell count is not sufficient. Match the height and width separately. The simplest safe rule for this exercise is to reuse the source's Rows.Count and Columns.Count in that order. If you deliberately intend a transpose, specify and verify the new relationship between keys and amounts.
Transfer a frozen result or install a live formula with intent
Imagine a closing process that wants the amount as it stood at 5 PM. The Review snippet's stored value is suited to that type of evidence. Its independent check tells the operator what was actually copied. The review record also needs a run date and the selected source file to establish which result belongs to which run. In a workbook where a reviewer wants to simulate alternate amount inputs, the live formula column is better suited: its output responds to changes while the control note confirms the source remains outside the write scope.
One test can demonstrate both outcomes. Change the source amount to a new number. In the formula lab see the existing J formula change at calculation, and in the snapshot lab see the existing G3 stay the same after D2 changes. Then run the copy routine and compare its new G3. Report the point when each output changed. Repeating a macro that installs formulas and repeating a macro that writes values can look the same on one run, while this extra edit proves they serve different users.
Run the two-workbook scope check
Prepare a non-macro workbook with a deliberately different source
Suppose a colleague's work in progress has a sheet named Orders. Give your exercise that same collision on purpose. In a new independent disposable workbook called CompareOrders.xlsx, add the Orders worksheet and enter 800 in G2. Leave J2 blank and put “Comparison workbook” in K1. Keep your RangePractice code workbook open separately with its known 64 in G2 and its original Notes marker. Use these two distinct source values to trace which workbook supplies the calculation.
With the comparison workbook in front, open the Macros dialog. If your desktop shows macros from all open workbooks, choose the entry whose code comes from RangePractice and verify that you selected the full requested name. If your version restricts the list, switch to the code workbook and test from its Notes tab instead. Both test paths give a useful ownership check. The first shows that the open and displayed workbook can differ from the workbook containing the running code. The second shows that the selector and worksheet displayed within the same workbook can differ from the explicitly named action target.
Read both results from their own workbooks
In RangePractice, expect J2 to read 67.20 from G2, 64. In CompareOrders, J2 should stay blank. If somebody instead operated on the comparison file, using its 800 and the same factor would produce 840. That would be reliable evidence of the wrong input association, even if the value itself was computed correctly. A different label in K1 and the different source amounts give you two independent ways to identify the workbook. Record the full names of both files so someone else can repeat your test.
The test reveals why a single glance at the active tab can mislead. From inside the code workbook, the worksheet lookup and explicit endpoints identify the same destination from different screen states. A routine intentionally written to transform whichever file is active has another contract. It needs a reliable way to find, verify and authorize the intended destination before writing. That different routine should be tested independently rather than using this lab's success to infer anything about it. When finished, close the comparison file or leave it within the training folder.
If your environment does not allow executing VBA, place the two expected results on a paper layout with the workbook names above the columns. Explain what the final lookup reads before you recalculate the amount. The pairing between source and destination is the skill under test.
Quick checks
Read each lookup before saying which cells changed
What does ws.Cells(2, 7) identify?
It identifies G2 on the worksheet assigned to ws. The first number is the worksheet row, the second the column position. If you add a Range as a receiver before Cells, those indices can have a different starting point. Inspect the whole expression and the object to its left.
Where should J11 get its value from in the formula lesson?
The relative expression uses the current row and three columns to the left. From J11 it reads G11. With 90 there, the fixed exercise factor produces 94.50. Read the bottom formula and verify the amount, since the first row alone could look right even if the rest reused the wrong source.
Why does the snapshot in G3 stay at 71 when the source becomes 81?
The snapshot procedure read the source's calculated value during its earlier run and wrote that value to Review. It did not transfer a live dependency. The formula in the source remains there, while the new result will reach the snapshot when you deliberately copy it again. Check the code and formula bars separately.
What does ClearContents preserve in the specific practice reset?
The clear removes the values or formulas in the reserved Review range while keeping its formatting. After running it on F3:G5, the headers in F2:G2 and the note in H3 are outside the affected range. The sum in H5 changes because the amounts are empty until you take a new snapshot.
Which block does CurrentRegion return around C2 in the snapshot fixture?
Within the blank edges, it returns C1:D4, including both headers and all three records. The code copies C2:D4 because the destination already has headers. A nearby connected value or missing separator can affect a CurrentRegion boundary, so inspect the address and decide whether it fits before using it as input.
How large is a source block from C2 through D5?
Rows two through five make four rows and C and D make two columns. Resizing a target from F3 with these dimensions covers F3:G6. Check whether the process owns those output cells before writing. The ability to compute the rectangle and the permission to replace its contents are separate.
Interview and discussion
Explain a real range bug from its evidence
How would you avoid writing to the wrong Orders sheet?
Choose the intended workbook explicitly, resolve Orders in it and store that worksheet reference. Qualify every range and endpoint with that same object. A dependable test keeps another tab or workbook active while verifying that only the intended known fixture changed. Compare an unrelated note on both sides.
Why can an unqualified Cells call cause a range construction to fail?
One endpoint can come from the currently active worksheet while Range or the other endpoint belongs to the intended worksheet. Excel needs endpoints on the same worksheet for this rectangle. Qualifying each endpoint avoids relying on selection and makes the mismatch visible when you read the code.
When would you use Value2 to transfer a multi-cell block?
Use it to read and write ordinary stored or calculated values when you want a snapshot, as in moving two fields over three records into a separate Review range. Keep their order and dimensions. This method differs from installing formulas or copying formatting. Confirm that the exercise puts the desired stored data in its own reserved region.
Why write a relative R1C1 formula instead of copying cells from another worksheet?
It expresses the dependence from each target cell directly. In every J row the formula refers to the same row at an offset of minus three columns. This does not move the current selection or depend on formatting or contents copied from the clipboard. Check the first and last targets after writing it.
How do two sets of six cells still make incompatible rectangle shapes?
Three rows by two columns and two rows by three columns both have six cells. In the snapshot they establish different positions for the keys and amounts, and the wider destination would include a note. Match the source and destination height and width independently. Establish what should happen before trying to extend the operation.
Six recall cards
- Workbook scope
ThisWorkbook refers to the code owner. A matching sheet name in another active file does not make it the same object.
- Address or numbers
Range names a visible address. Worksheet.Cells takes row then column, starting at one.
- Qualified endpoints
Use the same worksheet for both Cells endpoints under Range. Inspect minimum and maximum row and column before editing.
- Same-row formula
RC followed by a column offset evaluates relative to each destination. J with minus three columns reads from G.
- Snapshot
Write source values to a destination of matching height and width. Changes in the source need a new copy.
- Bound the edit
The formula output owns J2:J11 and its heading. The copy owns F3:G5. Their nearby note cells are outside each edit.
Microsoft references
Continue practising: explore the existing Excel Task Hub for additional exercises.