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.

Beginner 18 min read

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:

VBA
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 Sub
Different ways to write a Range

Range("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:

VBA
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 Sub
Cells with variables

The 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.

Tip. 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:

PropertyReturnsFor a cell showing $1,250.00
.ValueThe underlying value (dates as Date, currency as Currency)1250
.Value2The raw value, dates as serial numbers1250
.TextExactly what is displayed, as text$1,250.00
.FormulaThe formula in English A1 style, or the constant=B2*C2
.FormulaR1C1The formula in R1C1 style=RC[-2]*RC[-1]
.NumberFormatThe 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:

VBA
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
One line fills a formula down a whole column
ABC
1ProductQtyUnit price
2Printer paper A4104.5
3Stapler212.9
4Ballpoint pens (box)56.25
5Desk lamp134
6USB stick 64 GB48.75

Before: product, quantity and unit price

D2fx=B2*C2
ABCD
1ProductQtyUnit priceLine total
2Printer paper A4104.545.00
3Stapler212.925.80
4Ballpoint pens (box)56.2531.25
5Desk lamp13434.00
6USB stick 64 GB48.7535.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

VBA
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 Sub
Read, decide, write

Reading 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.

VBA
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 Sub
Offset relative to a found cell

ActiveCell 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:

VBA
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 Sub
Resize and Offset together

Resize(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:

VBA
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 Sub
Work with a block of unknown size

For 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.

Watch out. 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:

VBA
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 Sub
Formatting a header with With

Every 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

MethodRemoves
.ClearContentsValues and formulas, keeps formatting
.ClearFormatsFormatting only
.ClearEverything: values, formulas, formats
.ClearCommentsNotes (comments)
.DeleteThe cells themselves; cells below or to the right move up or left
VBA
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 Sub
Clear old results, keep the layout

Range("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:

VBA
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 Sub
Always say which sheet you mean

Notice 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

VBA
Range("B2").Select
Selection.Value = 100
Recorder style

write 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 Cells inside a qualified Range: Worksheets("Orders").Range(Cells(1, 1), Cells(5, 4)) fails when another sheet is active, because the inner Cells belong to the active sheet. Write .Cells inside a With Worksheets("Orders") block.
  • Swapping row and column: it is Cells(row, column), the opposite of the "A1" letter-first habit.
  • Reading .Value of a multi-cell range into a single variable: x = Range("A1:A5").Value gives an array, not a number. That is useful (Arrays in VBA: static, dynamic and fast range processing), but surprising the first time.
  • Using .Text for 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)?

2. What is Range("B2").Offset(2, 1)?

3. What does Range("A2").Resize(3, 2) refer to?

4. You assign "=B2*C2" to Range("D2:D6").Formula. What does D4 contain?

5. Which method empties cells but keeps their formatting?

⬇Practice workbookExamples with live formulas + practice sheets · .xlsx · 12 KB