You are on page 1of 29

The Complete Guide to

Ranges and Cells in


Excel VBA
PDF Version
By Paul Kelly ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 2

1. TABLE OF CONTENTS

1. Table of contents________________________________________________________ 2
2. Introduction ____________________________________________________________ 4
3. The Range Property _____________________________________________________ 5
4. The Cells Property of the Worksheet ________________________________________ 7
5. Using Cells and Range together ____________________________________________ 9
6. The Offset Property of Range _____________________________________________ 13
7. Using Rows and Columns as Ranges _______________________________________ 17
8. Using Range in place of Worksheet ________________________________________ 18
9. Reading Values from one Cell to another ___________________________________ 19
10. Reading Values to variables ____________________________________________ 21
11. How to Copy and Paste Cells____________________________________________ 23
12. Reading a Range of Cells to an Array _____________________________________ 25
13. Going through all the cells in a Range ____________________________________ 26
14. Formatting Cells _____________________________________________________ 27
15. Conclusion __________________________________________________________ 28
16. What's Next? ________________________________________________________ 29
17. Free Ebook __________________________________________________________ 29

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 3

"It is a capital mistake to theorize before one has data"- Sir Arthur Conan
Doyle

This eBook covers everything you need to know about using Cells and Ranges in
VBA. It is a pdf version of the post The Complete Guide to Ranges and Cells in Excel
VBA.

If you want information about using Range then check out the The Range Property.

For more information on using the Cells go to The Cells Property of the Worksheet
section.

Other topics included are The Offset Property of Range, Reading Values from
one Cell to another.

FUNCTION TAKES RETURNS EXAMPLE GIVES

Range cell address multiple cells .Range("A1:A4") $A$1:$A$4

Cells row, column one cell .Cells(1,5) $E$1

Offset row, column multiple cells Range("A1:A2") $C$2:$C$3


.Offset(1,2)

Rows row(s) one or more rows .Rows(4) $4:$4


.Rows("2:4") $2:$4

Columns column(s) one or more columns .Columns(4) $D:$D


.Columns("B:D") $B:$D

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 4

2. INTRODUCTION
This is the third post dealing with the three main elements of VBA. These three
elements are the Workbooks, Worksheets and Ranges/Cells. Cells are by far the most
important part of Excel. Almost everything you do in Excel starts and ends with Cells.

Generally speaking, you do three main things with Cells

1. Read
2. Write
3. Change the format

Excel has a number of methods for accessing cells such as Range, Cells and Offset.
"Why do I need them", "When should you use them?","Which is best ?" are questions
I am often asked.

In this post I will fully investigate each one of these methods of access and provide
you with answers to those questions.

Let's start with the simplest method of accessing cells - using the Range property of
the worksheet.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 5

3. THE RANGE PROPERTY


The worksheet has a Range property which you can use to access cells in VBA. The
Range property takes the same argument that most Excel Worksheet functions take
e.g. "A1", "A3:C6" etc.

The following example shows you how to place a value in a cell using the Range
property.

1 Public Sub WriteToCell()


2
3 ' Write number to cell A1 in sheet1 of this workbook
4 ThisWorkbook.Worksheets("Sheet1").Range("A1") = 67
5
6 ' Write text to cell A2 in sheet1 of this workbook
7 ThisWorkbook.Worksheets("Sheet1").Range("A2") = "John Smith"
8
9 ' Write date to cell A3 in sheet1 of this workbook
10 ThisWorkbook.Worksheets("Sheet1").Range("A3") = #11/21/2017#
11
12 End Sub

As you can see Range is a member of the worksheet which in turn is a member of the
Workbook. This follows the same hierarchy as in Excel so should be easy to
understand. To do something with Range you must first specify the workbook and
worksheet it belongs to.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 6

For the rest of this post I will use the code name of the sheet. This makes the code
clearer as I will not need to specify the workbook each time. You can use a sheet
directly with the code name as long as it is in the current workbook.

You can see the Code Name of the sheet in the VBAProject window. It is the name
outside the parenthesis.

The following code shows the above example using the Code Name of the worksheet.

1 Public Sub UsingCodeName()


2
3 ' Write number to cell A1 in sheet1 of this workbook
4 cnSheet1.Range("A1") = 67
5
6 ' Write text to cell A2 in sheet1 of this workbook
7 cnSheet1.Range("A2") = "John Smith"
8
9 ' Write date to cell A3 in sheet1 of this workbook
10 cnSheet1.Range("A3") = #11/21/2017#
11
12 End Sub

I will use the worksheet code name in the rest of the examples. It makes the code
much easier to read.

You can also write to multiple cells using the Range property

1 Public Sub WriteToMulti()


2
3 ' Write number to a range of cells
4 cnSheet1.Range("A1:A10") = 67
5
6 ' Write text to multiple ranges of cells
7 cnSheet1.Range("B2:B5,B7:B9") = "John Smith"
8
9 End Sub

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 7

4. THE CELLS PROPERTY OF THE


WORKSHEET
The worksheet object has another property called Cells which is very similar
to range.

There are two differences

1. Cells returns a range of one cell only


2. Cells takes row and column as arguments

The example below shows you how to write values to cells using both the Range and
Cells property

1 Public Sub UsingCells()


2
3 ' Write to A1
4 cnSheet1.Range("A1") = 10
5 cnSheet1.Cells(1, 1) = 10
6
7 ' Write to A10
8 cnSheet1.Range("A10") = 10
9 cnSheet1.Cells(10, 1) = 10
10
11 ' Write to E1
12 cnSheet1.Range("E1") = 10
13 cnSheet1.Cells(1, 5) = 10
14
15 End Sub

You may be wondering when you should use Cells and when you should use Range.

Using Range is useful for accessing the same cells each time the Macro runs. For
example, if you were using a Macro to calculate a total and write it to cell A10 every
time then Range would be suitable for this task.

Using the Cells property is useful if you are accessing a cell based on a number that
may vary. It is easier explain this with an example. The following code finds the first
blank cell in the first spreadsheet row and writes text to it.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 8

1 Public Sub WriteToFirstBlankCell()


2
3 ' Get last column from left that is not blank
4 Dim lLastCol As Integer
5 lLastCol = cnSheet1.Range("A1").End(xlToRight).Column
6
7 ' Write text to first blank cell in Row 1
8 cnSheet1.Cells(1, lLastCol + 1) = "John Smith"
9
10 End Sub

In this example we have the number of the column and the row. To use Range here
would require us to convert these values to the letter/number cell reference e.g. "C1".
Using the Cells property allows us to provide a row and a column number to access a
cell.

Sometimes you may want to return more than one cell using row and column
numbers. The next section shows you how to do this.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 9

5. USING CELLS AND RANGE TOGETHER


As you have seen you can only access one cell using the Cells property. If you want to
return a range of cells then you can use Cells with Ranges as follows

1 Public Sub UsingCellsWithRange()


2
3 With cnSheet1
4 ' Write 5 to Range A1:A10 using Cells property
5 .Range(.Cells(1, 1), .Cells(10, 1)) = 5
6
7 ' Format Range B1:Z1 to be bold
8 .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True
9
10 End With
11
12 End Sub

As you can see, you provide the start and end cell of the Range. Sometimes it can be
tricky to see which range you are dealing with when the value are all numbers. Range
has a property called Address which displays the letter/ number cell reference of
any range.

This can come in very handy when you are debugging or writing code for the first
time.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 10

In the following example we print out the address of the ranges we are using.

1 Public Sub ShowRangeAddress()


2
3 ' Note: Using underscore allows you to split up lines of code
4 With cnSheet1
5
6 ' Write 5 to Range A1:A10 using Cells property
7 .Range(.Cells(1, 1), .Cells(10, 1)) = 5
8 Debug.Print "First address is : " _
9 + .Range(.Cells(1, 1), .Cells(10, 1)).Address
10
11 ' Format Range B1:Z1 to be bold
12 .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True
13 Debug.Print "Second address is : " _
14 + .Range(.Cells(1, 2), .Cells(1, 26)).Address
15
16 End With
17
18 End Sub

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 11

In the example I used Debug.Print to print to the Immediate Window. To view this
window select View->Immediate Window (or Ctrl G)

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 12

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 13

6. THE OFFSET PROPERTY OF RANGE


Range has a property called Offset. The term Offset refers to a count from the
original position. It is used a lot in certain areas of programming.

With the Offset property you can get a Range of cells the same size and a certain
distance from the current range. The reason this is useful is that sometimes you may
want to select a Range based on a certain condition.

For example in the screenshot below there is a column for each day of the week.
Given the day number (i.e. Monday=1, Tuesday=2 etc.) we need to write the value to
the correct column.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 14

We will first attempt to do this without using Offset.

1 ' This sub tests with different values


2 Public Sub TestSelect()
3
4 ' Monday
5 SetValueSelect 1, 111.21
6 ' Wednesday
7 SetValueSelect 3, 456.99
8 ' Friday
9 SetValueSelect 5, 432.25
10 ' Sunday
11 SetValueSelect 7, 710.17
12
13 End Sub
14
15 ' Writes the value to a column based on the day
16 Public Sub SetValueSelect(lDay As Long, lValue As Currency)
17
18 Select Case lDay
19 Case 1: cnSheet1.Range("G3") = lValue
20 Case 2: cnSheet1.Range("H3") = lValue
21 Case 3: cnSheet1.Range("I3") = lValue
22 Case 4: cnSheet1.Range("J3") = lValue
23 Case 5: cnSheet1.Range("K3") = lValue
24 Case 6: cnSheet1.Range("L3") = lValue
25 Case 7: cnSheet1.Range("M3") = lValue
26 End Select
27
28 End Sub

As you can see in the example, we need to add a line for each possible option. This is
not an ideal situation. Using the Offset Property provides a much cleaner solution

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 15

1 ' This sub tests with different values


2 Public Sub TestOffset()
3
4 DayOffSet 1, 111.01
5 DayOffSet 3, 456.99
6 DayOffSet 5, 432.25
7 DayOffSet 7, 710.17
8
9 End Sub
10
11 Public Sub DayOffSet(lDay As Long, lValue As Currency)
12
13 ' We use the day value with offset specify the correct column
14 cnSheet1.Range("G3").Offset(, lDay) = lValue
15
16 End Sub

As you can see this solution is much better. If the number of days in increased then
we do not need to add any more code. For Offset to be useful there needs to be some
kind of relationship between the positions of the cells. If the Day columns in the
above example were random then we could not use Offset. We would have to use the
first solution.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 16

One thing to keep in mind is that Offset retains the size of the range. So
.Range("A1:A3").Offset(1,1) returns the range B2:B4. Below are some more examples
of using Offset.

1 Public Sub UsingOffset()


2
3 ' Write to B2 - no offset
4 cnSheet1.Range("B2").Offset() = "Cell B2"
5
6 ' Write to C2 - 1 column to the right
7 cnSheet1.Range("B2").Offset(, 1) = "Cell C2"
8
9 ' Write to B3 - 1 row down
10 cnSheet1.Range("B2").Offset(1) = "Cell B3"
11
12 ' Write to B3 - 1 column right and 1 row down
13 cnSheet1.Range("B2").Offset(1, 1) = "Cell C3"
14
15 ' Write to A1 - 1 column left and 1 row up
16 cnSheet1.Range("B2").Offset(-1, -1) = "Cell A1"
17
18 ' Write to range E3:G13 - 1 column right and 1 row down
19 cnSheet1.Range("D2:F12").Offset(1, 1) = "Cells E3:G13"
20
21 End Sub

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 17

7. USING ROWS AND COLUMNS AS RANGES


If you want to do something with an entire Row or Column you can use the Rows or
Columns property of the Worksheet. They both take one parameter which is the row
or column number you wish to access

1 Public Sub UseRowAndColumns()


2
3 ' Set the font size of column B to 9
4 cnSheet1.Columns(2).Font.Size = 9
5
6 ' Set the width of columns D to F
7 cnSheet1.Columns("D:F").ColumnWidth = 4
8
9 ' Set the font size of row 5 to 18
10 cnSheet1.Rows(5).Font.Size = 18
11
12 End Sub

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 18

8. USING RANGE IN PLACE OF WORKSHEET


You can also use Cells, Rows and Columns as part of a Range rather than part of a
Worksheet. You may have a specific need to do this but otherwise I would avoid the
practice. It makes the code more complex. Simple code is your friend. It reduces the
possibility of errors.

The code below will set the second column of the range to bold. As the range has only
two rows the entire column is considered B1:B2

1 Public Sub UseColumnsInRange()


2
3 ' This will set B1 and B2 to be bold
4 cnSheet1.Range("A1:C2").Columns(2).Font.Bold = True
5
6 End Sub

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 19

9. READING VALUES FROM ONE CELL TO


ANOTHER
In most of the examples so far we have written values to a cell. We do this by placing
the range on the left of the equals sign and the value to place in the cell on the right.

To write data from one cell to another we do the same. The destination range goes on
the left and the source range goes on the right. The following example shows you how
to do this

1 Public Sub ReadValues()


2
3 ' Place value from B1 in A1
4 cnSheet1.Range("A1") = cnSheet1.Range("B1")
5
6 ' Place value from B3 in sheet2 to cell A1
7 cnSheet1.Range("A1").Value = cnSheet2.Range("B3")
8
9 ' Place value from B1 in cells A1 to A5
10 cnSheet1.Range("A1:A5") = cnSheet1.Range("B1")
11
12 ' Will not work - You cannot read from multiple cells
13 cnSheet1.Range("A1:A5") = cnSheet1.Range("B1:B5")
14
15 End Sub

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 20

As you can see from this example it is not possible to read from multiple cells. If you
want to do this you can use the Copy function of Range with the Destination
parameter

1 Public Sub CopyValues()


2
3 ' Store the copy range in a variable
4 Dim rgCopy As Range
5 rgCopy = cnSheet1.Range("B1:B5")
6
7 ' Use this to copy from more than one cell
8 rgCopy.Copy Destination:=cnSheet1.Range("A1:A5")
9
10 ' You can paste to multiple destinations
11 rgCopy.Copy Destination:=cnSheet1.Range("A1:A5,C2:C6")
12
13 End Sub

The Copy function copies everything including the format of the cells. It is the same
result as manually copying and pasting a selection. You can see more about it in the
How to Copy and Paste Cells section.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 21

10. READING VALUES TO VARIABLES


The last section showed you how to read from one cell to another. You can also read
from a cell to a variable.

A variable is used to store values while a Macro is running. You normally do this
when you want to manipulate the data before writing it somewhere.

The following is a simple example using a variable. As you can see the value of the
item to the right of the equals is written to the item to the left of the equals.

1 Public Sub UseVar()


2
3 ' Create
4 Dim val As Integer
5
6 ' Read number from cell
7 val = cnSheet1.Range("A1")
8
9 ' Add 1 to value
10 val = val + 1
11
12 ' Write new value to cell
13 cnSheet1.Range("A2") = val
14
15 End Sub

To read text to a variable you use a variable of type String.

1 Public Sub UseVarText()


2
3 ' Declare a variable of type string
4 Dim sText As String
5
6 ' Read value from cell
7 sText = cnSheet1.Range("A1")
8
9 ' Write value to cell
10 cnSheet1.Range("A2") = sText
11
12 End Sub

You can write a variable to a range of cells. You just specify the range on the left and
the value will be written to all cells in the range.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 22

1 Public Sub VarToMulti()


2
3 ' Read value from cell
4 cnSheet1.Range("A1:B10") = 66
5
6 End Sub

You cannot read from multiple cells to a variable. However you can read to an array
which is a collection of variables. We will look at doing this in the next section.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 23

11. HOW TO COPY AND PASTE CELLS


If you want to copy and paste a range of cells then you do not need to select them.
This is a common error made by new VBA users.

You can simply copy a range of cells like this

1 Range("A1:B4").Copy Destination:=Range("C5")

Using this method copies everything values, formats, formulas and so on.
If you want to copy individual items you can use the PasteSpecial property of
range. It works like this

1 Range("A1:B4").Copy
2 Range("F3").PasteSpecial Paste:=xlPasteValues
3 Range("F3").PasteSpecial Paste:=xlPasteFormats
4 Range("F3").PasteSpecial Paste:=xlPasteFormulas

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 24

The following table shows a full list of all the paste types

PASTE TYPE
xlPasteAll
xlPasteAllExceptBorders
xlPasteAllMergingConditionalFormats
xlPasteAllUsingSourceTheme
xlPasteColumnWidths
xlPasteComments
xlPasteFormats
xlPasteFormulas
xlPasteFormulasAndNumberFormats
xlPasteValidation
xlPasteValues
xlPasteValuesAndNumberFormats

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 25

12. READING A RANGE OF CELLS TO AN


ARRAY
This section shows an awesome way to read data from a large number of cells with
very little code. It requires that you are familiar with arrays.

You can read data from a range of cells to an array in just one line of code. You can
also write back to a range of cells from an array in just one line. This is a remarkably
efficient way of getting a lot of values in one go. It saves you from having read the
cells one at a time.

The following code shows you how to do this.

1 Public Sub ReadToArray()


2
3 ' Create dynamic array
4 Dim StudentMarks() As Variant
5
6 ' Read 26 values into array from the first row
7 StudentMarks = Range("A1:Z1").Value
8
9 ' Write the 26 values to the third row
10 Range("A3:Z3").Value = StudentMarks
11
12 End Sub

Keep in mind that the array created by the read is a 2 dimensional array. This is
because a spreadsheet stores values in two dimensions i.e. rows and columns

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 26

13. GOING THROUGH ALL THE CELLS IN A


RANGE
Sometimes you may want to go through each cell one at a time to check value. You
can do this using a For Each loop shown in the following code

1 Public Sub TraversingCells()


2
3 ' Go through each cells in the range
4 Dim rg As Range
5 For Each rg In cnSheet1.Range("A1:A10,A20")
6 ' Print address of cells that are negative
7 If rg.Value < 0 Then
8 Debug.Print rg.Address + "is negative."
9 End If
10 Next
11
12 End Sub
13

You can also go through consecutive Cells using the Cells property and a
standard For loop. The standard loop is more flexible about the order you use but it
is slower than a For Each loop.

1 Public Sub TraverseCells()


2
3 ' Go through cells from A1 to A10
4 Dim i As Long
5 For i = 1 To 10
6 ' Print address of cells that are negative
7 If rg.Value < 0 Then
8 Debug.Print rg.Address + "is negative."
9 End If
10 Next
11
12 ' Go through cells in reverse i.e. from A10 to A1
13 Dim i As Long
14 For i = 10 To 1 Step -1
15 ' Print address of cells that are negative
16 If rg.Value < 0 Then
17 Debug.Print rg.Address + "is negative."
18 End If
19 Next
20
21 End Sub

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 27

14. FORMATTING CELLS


Sometimes you will need to format the cells the in spreadsheet. This is actually very
straightforward. The following example shows you various formatting you can add to
any range of cells

1 Public Sub FormattingCells()


2
3 With cnSheet1
4
5 ' Format the font
6 .Range("A1").Font.Bold = True
7 .Range("A1").Font.Underline = True
8 .Range("A1").Font.Color = rgbNavy
9
10 ' Set the number format to 2 decimal places
11 .Range("B2").NumberFormat = "0.00"
12 ' Set the number format to a date
13 .Range("C2").NumberFormat = "dd/mm/yyyy"
14 ' Set the number format to general
15 .Range("C3").NumberFormat = "General"
16 ' Set the number format to text
17 .Range("C4").NumberFormat = "Text"
18
19 ' Set the fill color of the cell
20 .Range("B3").Interior.Color = rgbSandyBrown
21
22 ' Format the borders
23 .Range("B4").Borders.LineStyle = xlDash
24 .Range("B4").Borders.Color = rgbBlueViolet
25
26 End With
27
28 End Sub

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 28

15. CONCLUSION
The following is a summary of the main points

1. The Range property of the Worksheet can be used to return a range of Cells.
It takes the number/letter reference e.g. A1:A56. It is best used when the
range will be the same each time the macro is run.
2. Use the Cells property of the Worksheet when the cell location is variable.
Cells return a range of one cell.
3. Use Range(Cells,Cells) to return more than one cell using
the Cells property.
4. Offset is used when the range is relative based on a condition e.g. the day of
the week.
5. You can use Columns and Rows when you require the entire column or row.
6. Cells, Columns and Rows are also members of Range but should be only
used this way if there is a specific need.
7. You can read from one cell to another by placing the destination cell on the
left of an equals sign and the source cells on the right.
8. You can write the value from one cell or variable to a range of cells in one line.
9. You cannot read from a range of cells in one line. To copy from multiple cells
you can use the Copy function with the Destination parameter.
10. You can read values from cells to variables and vice versa. You can write a
variable to a range of cells in one line.
11. Using arrays you there is a super-efficient way of reading from a Range of cells
to an array using just one line.
12. You can also write from an array to a range of cells in just one line.
13. You can use a For Each loop to run through every cell in a range.
14. You can also use a normal For loop. It is slower than For Each but allows
more flexibility on the order.
15. Formatting cells is straightforward once you have the range.

ExcelMacroMastery.com
THE COMPLETE GUIDE TO RANGES AND CELLS IN EXCEL 29

16. WHAT'S NEXT?


Cells are one of the three most important element of Excel VBA. You can check out
the other two elements here:

The Complete guide to the VBA Workbook.


The complete guide to Worksheets in Excel VBA.

You can view a list of all the VBA posts on my blog here.

17. FREE EBOOK

If you would like to receive a free eBook and exclusive content not available on my
blog then you can sign up here

ExcelMacroMastery.com

You might also like