VBA course · Lesson 6 of 33
Range and Cells: working with cells in VBA
Refer to cells with Range and Cells, read and write values and formulas, use Offset, Resize, CurrentRegion, With blocks, formatting and clearing.
Almost every Excel macro reads or changes cells, so the Range object is the one you will use most. This lesson shows the different ways to point at cells, how to read and write their values and formulas, how to move around with Offset and Resize, and how to format and clear them. Along the way you will build a small macro that completes an order list.
Range: cells by address
Range takes an address in the same notation you use in formulas:
Option Explicit
Sub RangeExamples()
Range("A1").Value = "Order list" ' one cell
Range("A3:D3").Font.Bold = True ' a block of cells
Range("A3:A10,C3:C10").Interior.Color = RGB(242, 242, 242) ' two areas
Range("A3", "D10").Borders.LineStyle = xlContinuous ' corners
Range("F:F").ColumnWidth = 14 ' a whole column
Range("12:12").RowHeight = 24 ' a whole row
End SubRange("A3", "D10") takes the two corner cells and means the same as Range("A3:D10"). That form is handy when the corners come from variables. You can also use a named range: if you named a cell VatRate in the Name Box, Range("VatRate") refers to it, and the code keeps working when someone inserts rows above it.
Cells: cells by row and column number
Cells(row, column) refers to a single cell by numbers. Cells(3, 2) is B3: row 3, column 2. The column may also be a letter: Cells(3, "B"). Numbers are what make Cells powerful, because they can come from variables and loops:
Option Explicit
Sub NumberTheRows()
Dim r As Long
' Write 1 to 5 into A4:A8
For r = 4 To 8
Cells(r, 1).Value = r - 3
Next r
End SubThe For ... Next loop runs the line five times, with r = 4, 5, 6, 7, 8. You will learn loops in For loops: For...Next and For Each; for now just notice how Cells(r, 1) moves down one row each time. You can combine both styles: Range(Cells(4, 1), Cells(8, 4)) is A4:D8.
Range("A1") is easier to read for fixed cells. Cells(r, c) is better whenever the position is calculated. Most real macros use both.Value, Value2, Text and Formula
A cell has several properties that look alike but answer different questions:
| Property | Returns | For a cell showing $1,250.00 |
|---|---|---|
| .Value | The underlying value (dates as Date, currency as Currency) | 1250 |
| .Value2 | The raw value, dates as serial numbers | 1250 |
| .Text | Exactly what is displayed, as text | $1,250.00 |
| .Formula | The formula in English A1 style, or the constant | =B2*C2 |
| .FormulaR1C1 | The formula in R1C1 style | =RC[-2]*RC[-1] |
| .NumberFormat | The format code | $#,##0.00 |
.Value is the default property: Range("A1") = 5 works, but writing .Value explicitly makes code clearer, and this course always does. .Text depends on column width (a narrow column shows ####), so do not use it for calculations.
Writing formulas from VBA
Assign a string that starts with = to .Formula and Excel enters a real formula. If you assign it to a whole range, Excel adjusts the relative references for each row, exactly as if you had filled it down:
Option Explicit
Sub AddLineTotals()
' Headers in row 1, data in rows 2 to 6
Range("D1").Value = "Line total"
Range("D2:D6").Formula = "=B2*C2"
Range("D2:D6").NumberFormat = "#,##0.00"
End Sub| A | B | C | |
|---|---|---|---|
| 1 | Product | Qty | Unit price |
| 2 | Printer paper A4 | 10 | 4.5 |
| 3 | Stapler | 2 | 12.9 |
| 4 | Ballpoint pens (box) | 5 | 6.25 |
| 5 | Desk lamp | 1 | 34 |
| 6 | USB stick 64 GB | 4 | 8.75 |
Before: product, quantity and unit price
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Product | Qty | Unit price | Line total |
| 2 | Printer paper A4 | 10 | 4.5 | 45.00 |
| 3 | Stapler | 2 | 12.9 | 25.80 |
| 4 | Ballpoint pens (box) | 5 | 6.25 | 31.25 |
| 5 | Desk lamp | 1 | 34 | 34.00 |
| 6 | USB stick 64 GB | 4 | 8.75 | 35.00 |
After AddLineTotals: D2:D6 hold =B2*C2, =B3*C3 and so on
Result: 45.00
Always write formulas with English function names and commas, whatever language your Excel uses; .Formula is translated for display automatically. For dynamic-array formulas that should spill, such as FILTER or UNIQUE, use .Formula2 instead (see Using Excel worksheet functions in VBA).
Reading values into variables
Option Explicit
Sub CheckStock()
Dim product As String
Dim inStock As Long
Dim reorderLevel As Long
product = Range("A2").Value
inStock = Range("B2").Value
reorderLevel = Range("C2").Value
If inStock <= reorderLevel Then
Range("D2").Value = "Reorder"
Range("D2").Font.Color = RGB(192, 0, 0) ' dark red
Else
Range("D2").Value = "OK"
Range("D2").Font.Color = RGB(0, 128, 0) ' green
End If
End SubReading cells into well-named variables (Variables and data types: Dim, Option Explicit and scope) makes the logic read almost like English.
Moving around: Offset
Offset(rows, columns) returns a range shifted from another one. Positive numbers go down and right, negative numbers up and left. Range("B5").Offset(1, 2) is D6. Offset does not move the selection; it just points somewhere else.
Option Explicit
Sub LabelNextToActiveCell()
' Write a note one column to the right of whatever cell is selected,
' and the user's name two columns to the right
ActiveCell.Offset(0, 1).Value = "Checked"
ActiveCell.Offset(0, 2).Value = Application.UserName
End SubActiveCell is the single cell with the thick border in the active window. Use it when a macro should work where the user is; use explicit addresses otherwise.
Changing size: Resize
Resize(rows, columns) keeps the top-left cell and changes the size of the range. Range("A2").Resize(5, 4) is A2:D6. Together with Offset it lets you describe a block of data without knowing its address in advance:
Option Explicit
Sub FormatDataBelowHeader()
Dim header As Range
Dim dataRows As Long
Set header = Range("A1:D1")
dataRows = 5
header.Font.Bold = True
' The data block: one row below the header, same width, 5 rows tall
header.Offset(1, 0).Resize(dataRows).Interior.Color = RGB(255, 255, 240)
End SubResize(dataRows) with only one argument keeps the column count. Later you will calculate dataRows from the last filled row (Find the last row and build dynamic ranges in VBA).
CurrentRegion: the whole block
CurrentRegion returns the rectangular block of data around a cell, up to the first completely empty row and column, exactly what Ctrl+A selects when you are inside a list (Ctrl+Shift+8 on Windows). It is the quickest way to grab a table of unknown size:
Option Explicit
Sub DescribeOrderList()
Dim block As Range
Set block = Range("A1").CurrentRegion
MsgBox "The list is " & block.Address & vbNewLine & _
block.Rows.Count & " rows (incl. header) and " & _
block.Columns.Count & " columns."
' Add borders to every cell of the block
block.Borders.LineStyle = xlContinuous
End SubFor the order list above, the message reads The list is $A$1:$D$6, 6 rows and 4 columns. Rows.Count, Columns.Count and Address are properties every range has. Cells.Count gives the number of cells.
CurrentRegion stops at the first blank row. If your data has empty rows in the middle, it returns only part of it. Fix the data or use the last-row techniques of lesson 23.The With block
When several lines work on the same object, With saves typing and makes the code faster, because Excel finds the object only once:
Option Explicit
Sub StyleHeader()
With Range("A1:D1")
.Font.Bold = True
.Font.Color = vbWhite
.Interior.Color = RGB(31, 78, 121) ' dark blue
.HorizontalAlignment = xlCenter
.RowHeight = 22
End With
End SubEvery line inside the block that starts with a dot belongs to Range("A1:D1"). Blocks can be nested (With .Font ... End With inside), but do not overdo it.
Clearing and deleting
| Method | Removes |
|---|---|
| .ClearContents | Values and formulas, keeps formatting |
| .ClearFormats | Formatting only |
| .Clear | Everything: values, formulas, formats |
| .ClearComments | Notes (comments) |
| .Delete | The cells themselves; cells below or to the right move up or left |
Option Explicit
Sub ResetOrderList()
' Keep the headers in row 1, wipe the data below
Range("A2:D100").ClearContents
' Delete row 1 entirely? Use: Rows(1).Delete
End SubRange("A5").EntireRow.Delete deletes the whole row 5, and Range("C1").EntireColumn.Insert inserts a new column C.
Worksheet-qualified ranges
So far every Range referred to the active sheet. That is fine for quick macros, but dangerous in real ones: if the user clicks another sheet, the macro writes into the wrong place. Put the sheet in front of the range:
Option Explicit
Sub WriteToOrdersSheet()
With Worksheets("Orders")
.Range("A1").Value = "Order list"
.Range("F1").Value = "Updated " & Format(Now, "yyyy-mm-dd hh:nn")
.Cells(2, 4).Formula = "=B2*C2"
End With
End SubNotice the dots in front of .Range and .Cells. Without them, those calls would refer to the active sheet again. Workbooks and worksheets in VBA covers sheets in detail.
Avoid Select
The macro recorder selects everything, but your code does not need to. Instead of
Range("B2").Select
Selection.Value = 100write Range("B2").Value = 100. It is shorter, faster, works on sheets that are not active, and does not move the user's cursor. Select a cell only when you deliberately want to show the user where something is.
Common mistakes
- Unqualified
Cellsinside a qualifiedRange:Worksheets("Orders").Range(Cells(1, 1), Cells(5, 4))fails when another sheet is active, because the innerCellsbelong to the active sheet. Write.Cellsinside aWith Worksheets("Orders")block. - Swapping row and column: it is
Cells(row, column), the opposite of the "A1" letter-first habit. - Reading
.Valueof a multi-cell range into a single variable:x = Range("A1:A5").Valuegives an array, not a number. That is useful (Arrays in VBA: static, dynamic and fast range processing), but surprising the first time. - Using
.Textfor calculations: it is formatted text and may be####. - Local formula syntax:
.Formula = "=SUMME(A1:A5)"fails in German Excel; use English names (=SUM(A1:A5)) or.FormulaLocal.
Check yourself
1. Which cell is Cells(4, 3)?
Cells takes the row first, then the column: row 4, column 3 (C).
2. What is Range("B2").Offset(2, 1)?
Two rows down from row 2 is row 4, one column right from B is C.
3. What does Range("A2").Resize(3, 2) refer to?
Resize keeps the top-left cell and makes the range 3 rows tall and 2 columns wide.
4. You assign "=B2*C2" to Range("D2:D6").Formula. What does D4 contain?
Excel adjusts relative references for every cell in the range, as with Fill Down.
5. Which method empties cells but keeps their formatting?
ClearContents removes values and formulas only. Clear removes formatting too, and Delete removes the cells themselves.