The Complete Guide to Ranges and Cells in Excel VBA

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


Excel Range

© Boyfriend | Dreamstime.comNumbers Photo


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. Everything you do in Excel starts and/or ends with Cells.


Generally speaking, you do three main things with Cells



Read
Write
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.


The first section provides a  quick reference to Cells and Ranges. In the second section we will start with the simplest method – using the Range property of the worksheet.

 


A Quick Guide to Cells and Ranges

The following table gives a breakdown of different ways of accessing cells





Function
You provide
It returns a range of
Example


Range
Cell Address
Multiple Cells
.Range(“A1:A4″)


Cells
Row , Column
One Cell
.Cells(1,5)


Offset
Row , Column
Multiple Cells
.Offset(1,2)


Rows
Row
Multiple Cells
.Rows(10)


Columns
Column
Multiple Cells
.Columns(4)



 


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.



Public Sub WriteToCell()

' Write number to cell A1 in sheet1 of this workbook
ThisWorkbook.Worksheets("Sheet1").Range("A1") = 67

' Write text to cell A2 in sheet1 of this workbook
ThisWorkbook.Worksheets("Sheet1").Range("A2") = "John Smith"

' Write date to cell A3 in sheet1 of this workbook
ThisWorkbook.Worksheets("Sheet1").Range("A3") = #11/21/2017#

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.


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. Please read the post on Worksheets for more details to using the code name of a worksheet.


The following code shows the above example using the code name of the keyword.



Public Sub UsingCodeName()

' Write number to cell A1 in sheet1 of this workbook
cnSheet1.Range("A1") = 67

' Write text to cell A2 in sheet1 of this workbook
cnSheet1.Range("A2") = "John Smith"

' Write date to cell A3 in sheet1 of this workbook
cnSheet1.Range("A3") = #11/21/2017#

End Sub

You can also write to multiple cells using the Range property



Public Sub WriteToMulti()

' Write number to a range of cells
cnSheet1.Range("A1:A10") = 67

' Write text to multiple ranges of cells
cnSheet1.Range("B2:B5,B7:B9") = "John Smith"

End Sub

 


The Cells Property of the Worksheet

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


There are two differences



Cells returns a range of one cell only
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



Public Sub UsingCells()

' Write to A1
cnSheet1.Range("A1") = 10
cnSheet1.Cells(1, 1) = 10

' Write to A10
cnSheet1.Range("A10") = 10
cnSheet1.Cells(10, 1) = 10

' Write to E1
cnSheet1.Range("E1") = 10
cnSheet1.Cells(1, 5) = 10

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.



Public Sub WriteToFirstBlankCell()

' Get last column from left that is not blank
Dim lLastCol As Integer
lLastCol = cnSheet1.Range("A1").End(xlToRight).Column

' Write text to first blank cell in Row 1
cnSheet1.Cells(1, lLastCol + 1) = "John Smith"

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.


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



Public Sub UsingCellsWithRange()

With cnSheet1
' Write 5 to Range A1:A10 using Cells property
.Range(.Cells(1, 1), .Cells(10, 1)) = 5

' Format Range B1:Z1 to be bold
.Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True

End With

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.


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



Public Sub ShowRangeAddress()

' Note: Using underscore allows you to split up lines of code
With cnSheet1

' Write 5 to Range A1:A10 using Cells property
.Range(.Cells(1, 1), .Cells(10, 1)) = 5
Debug.Print "First address is : " _
+ .Range(.Cells(1, 1), .Cells(10, 1)).Address

' Format Range B1:Z1 to be bold
.Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True
Debug.Print "Second address is : " _
+ .Range(.Cells(1, 2), .Cells(1, 26)).Address

End With

End Sub

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


ImmediateWindow


 


ImmediateSampeText


 


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.


CellsRanges_Sheet


We will first attempt to do this without using Offset.



' This sub tests with different values
Public Sub TestSelect()

' Monday
SetValueSelect 1, 111.21
' Wednesday
SetValueSelect 3, 456.99
' Friday
SetValueSelect 5, 432.25
' Sunday
SetValueSelect 7, 710.17

End Sub

' Writes the value to a column based on the day
Public Sub SetValueSelect(lDay As Long, lValue As Currency)

Select Case lDay
Case 1: cnSheet1.Range("G3") = lValue
Case 2: cnSheet1.Range("H3") = lValue
Case 3: cnSheet1.Range("I3") = lValue
Case 4: cnSheet1.Range("J3") = lValue
Case 5: cnSheet1.Range("K3") = lValue
Case 6: cnSheet1.Range("L3") = lValue
Case 7: cnSheet1.Range("M3") = lValue
End Select

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



' This sub tests with different values
Public Sub TestOffset()

DayOffSet 1, 111.01
DayOffSet 3, 456.99
DayOffSet 5, 432.25
DayOffSet 7, 710.17

End Sub

Public Sub DayOffSet(lDay As Long, lValue As Currency)

' We use the day value with offset specify the correct column
cnSheet1.Range("G3").Offset(, lDay) = lValue

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.


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



Public Sub UsingOffset()

' Write to B2 - no offset
cnSheet1.Range("B2").Offset() = "Cell B2"

' Write to C2 - 1 column to the right
cnSheet1.Range("B2").Offset(, 1) = "Cell C2"

' Write to B3 - 1 row down
cnSheet1.Range("B2").Offset(1) = "Cell B3"

' Write to B3 - 1 column right and 1 row down
cnSheet1.Range("B2").Offset(1, 1) = "Cell C3"

' Write to A1 - 1 column left and 1 row up
cnSheet1.Range("B2").Offset(-1, -1) = "Cell A1"

' Write to range E3:G13 - 1 column right and 1 row down
cnSheet1.Range("D2:F12").Offset(1, 1) = "Cells E3:G13"

End Sub

 


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



Public Sub UseRowAndColumns()

' Set the font size of column B to 9
cnSheet1.Columns(2).Font.Size = 9

' Set the width of columns D to F
cnSheet1.Columns("D:F").ColumnWidth = 4

' Set the font size of row 5 to 18
cnSheet1.Rows(5).Font.Size = 18

End Sub

 


Using Range in place of Worksheet

You can also use Offsets, Cells, Rows and Columns as part of Range. 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 refers to two rows the entire column is considered B1:B2



Public Sub UseColumnsInRange()

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

End Sub

 


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



Public Sub ReadValues()

' Place value from B1 in A1
cnSheet1.Range("A1") = cnSheet1.Range("B1")

' Place value from B3 in sheet2 to cell A1
cnSheet1.Range("A1").Value = cnSheet2.Range("B3")

' Place value from B1 in cells A1 to A5
cnSheet1.Range("A1:A5") = cnSheet1.Range("B1")

' Will not work - You cannot read from multiple cells
cnSheet1.Range("A1:A5") = cnSheet1.Range("B1:B5")

End Sub

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



Public Sub CopyValues()

' Use this to copy from more than one cell
cnSheet1.Range("B1:B5").Copy Destination:=cnSheet1.Range("A1:A5")

' You can paste to multiple destinations
cnSheet1.Range("B1:B5").Copy Destination:=cnSheet1.Range("A1:A5,C2:C6")

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.


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.



Public Sub UseVar()

' Create
Dim val As Integer

' Read number from cell
val = cnSheet1.Range("A1")

' Add 1 to value
val = val + 1

' Write new value to cell
cnSheet1.Range("A2") = val

End Sub

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



Public Sub UseVarText()

' Declare a variable of type string
Dim sText As String

' Read value from cell
sText = cnSheet1.Range("A1")

' Write value to cell
cnSheet1.Range("A2") = sText

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.



Public Sub VarToMulti()

' Read value from cell
cnSheet1.Range("A1:B10") = 66

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.


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.



Public Sub ReadToArray()

' Create dynamic array
Dim StudentMarks() As Variant

' Read 26 values into array from sheet1
StudentMarks = ThisWorkbook.Worksheets("Sheet1").Range("A1:Z1").Value

' Write the 26 values to the third row of sheet2
ThisWorkbook.Worksheets("Sheet2").Range("A3:Z3").Value = StudentMarks

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


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



Public Sub TraversingCells()

' Go through each cells in the range
Dim rg As Range
For Each rg In cnSheet1.Range("A1:A10,A20")
' Print address of cells that are negative
If rg.Value < 0 Then
Debug.Print rg.Address + "is negative."
End If
Next

End Sub


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.



Public Sub TraverseCells()

' Go through cells from A1 to A10
Dim i As Long
For i = 1 To 10
' Print address of cells that are negative
If rg.Value < 0 Then
Debug.Print rg.Address + "is negative."
End If
Next

' Go through cells in reverse i.e. from A10 to A1
Dim i As Long
For i = 10 To 1 Step -1
' Print address of cells that are negative
If rg.Value < 0 Then
Debug.Print rg.Address + "is negative."
End If
Next

End Sub

 


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



Public Sub FormattingCells()

With cnSheet1

' Format the font
.Range("A1").Font.Bold = True
.Range("A1").Font.Underline = True
.Range("A1").Font.Color = rgbNavy

' Set the number format to 2 decimal places
.Range("B2").NumberFormat = "0.00"
' Set the number format to a date
.Range("C2").NumberFormat = "dd/mm/yyyy"
' Set the number format to general
.Range("C3").NumberFormat = "General"
' Set the number format to text
.Range("C4").NumberFormat = "Text"

' Set the fill color of the cell
.Range("B3").Interior.Color = rgbSandyBrown

' Format the borders
.Range("B4").Borders.LineStyle = xlDash
.Range("B4").Borders.Color = rgbBlueViolet

End With

End Sub

 


Conclusion

I hope you enjoyed this post and found it beneficial. The following is a summary of the main points



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.
Use the Cells property of the Worksheet when the cell location is variable. Cells return a range of one cell.
Use Range(Cells,Cells) to return more than one cell using the Cells property.
Offset is used when the range is relative based on a condition e.g. the day of the week.
You can use Columns and Rows when you require the entire column or row.
Cells, Columns and Rows are also members of Range but should be only used this way if there is a specific need.
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.
You can write the value from one cell or variable to a range of cells in one line.
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.
You can read values from cells to variables and vice versa. You can write a variable to  a range of cells in one line.
Using arrays you there is a super efficient way of reading from a Range of cells to an array using just one line.
You can also write from an array to a range of cells in just one line.
You can use a For Each loop to run through every cell in a range.
You can also use a normal For loop. It is slower than For Each but allows more flexibility on the order.
Formatting cells is straightforward once you have the range.

 •  0 comments  •  flag
Share on Twitter
Published on January 02, 2015 12:53
No comments have been added yet.