The Complete Guide to Ranges and Cells in Excel VBA

VBA Range

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

This post covers everything you need to know about using Cells and Ranges in VBA. You can read it from start to finish as it is layed out in a logical order. If you prefer you can use the table of contents below to go to a section of your choice.

If you want information about using Range then check out the Range property section.

For more information on using the Cells go to the Cells property section.

Other topics included are Offset property, reading values between cells, reading values to arrays and formatting cells.

 
 

A Quick Guide to Ranges and Cells

FunctionTakesReturns ExampleGives

Range

cell addressmultiple cells.Range("A1:A4")$A$1:$A$4
Cellsrow, columnone cell.Cells(1,5)$E$1
Offsetrow, columnmultiple cellsRange("A1:A2")
.Offset(1,2)
$C$2:$C$3
Rowsrow(s)one or more rows.Rows(4)
.Rows("2:4")
$4:$4
$2:$4
Columnscolumn(s)one or more columns.Columns(4)
.Columns("B:D")
$D:$D
$B:$D

 
 

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.

 
 

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.

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

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

 
 

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

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

 
 
CLICK HERE TO DOWNLOAD THE FREE PDF VERSION OF THIS POST  

 
 

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

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

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()

    ' Store the copy range in a variable
    Dim rgCopy As Range
    Set rgCopy = cnSheet1.Range("B1:B5")

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

    ' You can paste to multiple destinations
    rgCopy.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. You can see more about it in the Copying and Pasting Cells section.

 
 

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.

 
 

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

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

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

 
 
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

 
 

Reading a Range of Cells to an Array

You can also copy values by assigning the value of one range to another.

Range("A3:Z3").Value = Range("A1:Z1").Value

 
 
The value of  range in this example is considered to be a variant array. What this means is that you can easily read from a range of cells to an array. You can also write from an array to a range of cells. If you are not familiar with arrays you can check them out in this post:  The Complete Guide to Arrays in Excel VBA.  

 
 
The following code shows an example of using an array with a range.

Public Sub ReadToArray()

    ' Create dynamic array
    Dim StudentMarks() As Variant

    ' Read 26 values into array from the first row
    StudentMarks = Range("A1:Z1").Value

    ' Do something with array here

    ' Write the 26 values to the third row
    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 Range("A" & i).Value < 0 Then
            Debug.Print Range("A" & i).Address + " is negative."
        End If
    Next
 
    ' Go through cells in reverse i.e. from A10 to A1
    For i = 10 To 1 Step -1
        ' Print address of cells that are negative
        If Range("A" & i) < 0 Then
            Debug.Print Range("A" & i).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

 
 

Main Points

The following is a summary of the main points

  1. Range returns a range of cells
  2. Cells returns one cells only
  3. You can read from one cell to another
  4. You can read from a range of cells to another range of cells.
  5. You can read values from cells to variables and vice versa.
  6. You can read values from ranges to arrays and vice versa
  7. You can use a For Each or For loop to run through every cell in a range.
  8. The properties Rows and Columns allow you to access a range of cells of these types

 
 

What’s Next?

The three most important elements of VBA are Workbooks, Worksheets and Cells and Ranges. If you feel you have a good understanding of these the you may want to check out The Ultimate Guide to Loops in Excel VBA. You can also view a list of all the VBA posts here.

 
 

Free PDF of this Post

 
 
  CLICK HERE TO DOWNLOAD THE FREE PDF VERSION OF THIS POST  

 
 
Note: I periodically archive comments to maintain the page speed.

54 comments

  1. Hi Paul,

    I was able to get your Dim code to work in its own sheet referencing another, and accumulate using Private Sub Worksheet_Calculate(), instead of Change.

    Thanks for the assistance. I learned alot.

    David

  2. Hi Paul,

    You are Great!

    Thank you for the code.
    I require your help throughout my learning of VBA programming. Will go with your suggestion master in VBA. Thank you so much for helping and guiding me through your informative blog.

    Keep doing the good work..
    Regards
    Ravindra

  3. Hi Paul!

    Still learning a lot with your website!

    I have a question about looping through a range of cells containing percentage numbers stored as text.

    I’m having a though time trying to convert these text stored percentages into numbers through vba.

    do you have any tips?

    Thanks!

    1. Hi Eduardo,

      The code below will place the percentage text values in a1:a10 into b1:b10 as percentage numbers

      Dim c As Variant
      For Each c In Range("a1:A10")
          ' Write as percentage to B1, B2 etc.
          c.Offset(0, 1) = c.value
          c.Offset(0, 1).NumberFormat = "0.00%"
      Next
      
  4. Hi Paul,

    1) Is it possible to send a keystroke to other applications using VBA!?
    2) I have a software in which so many popups will be generated and it will unnecessarily distract the work. Is it possible to close those popups using VBA code, If yes can you please post some sample code in your blog.

    Regards

    1. Hi,

      1. You can send keys by using the windows API through VBA – this is pretty advanced if you haven’t done this before. This article shows how to do it with C#. You would use the same WinAPI calls using VBA.

      2. Using the WinAPI you can post events that will click OK buttons etc. on popups. To have VBA do this when you are using the software could be very tricky. Again this is very advanced if you have no experience of WinAPI.

      Regards
      Paul

  5. i use vba code below to convert textbox to cell but it only convert to column A only . How i can improve it to whole page? Textbox are in different column.

    Sub TextBoxCopy()
    Sheets(“Page 1”).Select
    x = 1
    For Each tbox In ActiveSheet.TextBoxes
    Range(“a” & x).Value = tbox.Text
    Range(“a” & x).WrapText = off
    x = x + 1
    Next tbox
    Sheets(“Page 1”).Columns(“A”).AutoFit
    End Sub

    1. You can use tbox.TopLeftCell.Row and tbox.TopLeftCell.Column to get the cells where the TextBox is and then use these to write to the appropriate cell.

  6. Hi Paul:
    I’m having some problems with a macro. I have columns from B to DA, every column has 60 cells that starts at the cell 12 and end at 72. The column B has symbol and C has a number, D(symbol) and E(value) and so on until DA. Here is what I want to do. Go from the cell 72 to cell 12 (down to up) search for the first 36 cells with a number on it “ ignoring blank cells” and delete the rest upwards, also delete whatever is to the left of the deleted value, and apply a cell color to deleted cells.. If any of the column has 36 data or less, do nothing.

  7. Paul –

    Thanks, this is working perfectly! I figured I would be able to use an array, but couldn’t figure out the details.

  8. Hi,
    I’m having difficulty in creating a VBA code that will make, insert a list of values from column (A) to just blank cells of column (B), respectively. Because of so many row and cells, filling blank cells is so difficult, manually. Please help me.
    Thanks in advance
    Here is a sample of data:
    (A) (B) To become Like this
    3 — 3
    3 1001 1001
    9 1002 1002
    15 — 3
    45 2100 2100
    7 745 745
    — 9
    — 15
    — 45
    3500 3500
    — 7

  9. Hello,

    I have been a problem that nobody can solved in France.

    I have thousands and thousands cells that contain only VBA code :
    For example : the cell $A$2 contains
    “range(“Lubunit”).value = 1 and range(“cooler”).value = 10″

    Normally, in VBA, I should have to type :
    If range(“Lubunit”).value = 1 and range(“cooler”).value = 10 then …

    How could I get the value of the cell $A$2 directly in VBA ?

    I tried :
    If range(“$A$2”).value then .. —> error 13

    or

    Dim condition as string
    Condition = range(“$a$2”).value
    If condition = True then … —> error 13

    Please, do you have an idea to solve my problem ?

    thanks in advance

    1. Hi Halley,

      Storing VBA code in a cell is very strange to say the least.
      If all the cells have the same format then you could parse the string using Split. You take the named range and value from the string and then using them in your VBA code to build the If statememt.

    1. Square brackets are not “short-hand notation”. They are actually a shortcut for calling the Evaluate function.

  10. Hi Paul,

    Nice and ultimate blog, You are having a great knowledge and command over the VBA.
    Thanks for the blog.

    I need a small help in reading and writing the values from array in VBA.

    I have stucked in between and I could not able to get the desired outpud due to the same. It would be highly obliged if you could help me to do so.

    many thanks in advance.

    Following snippet of sentences are in a For loop and the values should be iterated with the increment in the loop variable (string array num(i) contains strings) and should display the output in column B with increment rowise.

    ActiveSheet.Range(“$A$1:$X$55”).AutoFilter Field:=1, Criteria1:= _
    “= num(i).Value”, Operator:=xlAnd

    Sheet2.Range(“$B29(i)”).Value = tot

    [num(i).value is not getting picked up and the $B2(i) is a syntax error due to which it is not printing the values ]

    1. Hi Sanket,

      Using “B29(i)” doesn’t make sense here. The Range property expects an Excel range so a valid one it should be something like Range(“$B” & i).
      If you want to start from B29 you can use

      Range("$B29").Offset(i).Value = tot 
      

      which counts i rows from B29.

  11. 123 4:07:56 PM
    456 4:18:28 PM
    123 4:18:36 PM <—–
    999 9:28:34 AM
    Hi good day. i am looking help from you.
    I am using vba user form to find the second Set of ("123") in the worksheet based on the latest time.
    Can i know anything idea from you? sorry for duplicate the submition.
    Thanks
    rick

    1. Hi Rick,

      Use a For loop to read through the items. Set the time a zero. When you find 123 check if the time is greater than stored and if so store the row. Repeat until end of data.

  12. Hello
    I usually do all me excel programming using a cells feature to create dynamic access but thought I would look at combining this with ranges.

    The following two lines do the same thing, i.e. select a block of cells

    ‘First a rectangle of cells
    ‘Set rng = Range(“c4:g10”)
    ‘Set rng = Range(Cells(4, 3), Cells(10, 7))

    The first bit now defines three separate rows
    ‘Now three separate rows
    ‘Set rng = Range(“c4:g4,c6:g6,c10:g10”)

    but gives errors if I try to build the same code using cells with the following structure (two rows to start with)

    Set rng = Range((Cells(4, 3), Cells(4, 7)), (Cells(6, 3), Cells(6, 7)))

    Any ideas.
    Bob

      1. Many thanks. Its strange that the philosophy changes when the method of defining cells changes. Consistency would have been nice!
        Bob

  13. hi Paul,
    nice to read your article.
    I need your help 🙂

    I have a workbook that contains macro, and list of the activity, for example
    A1 B1 C1 D1
    ND NB NC ND
    MD NR NT NF
    from that list, i want to open workbook that contains the value on that rows, for example i want to open workbook C:dataND-NB-NC.xlsx
    after the workbook was opened, and the close, open another workbook on the next row list, like C:dataMD-NR-NT.xlsx

    can you give some advice and solution for my problem..

    Thank you very much for your attention

    1. Hi Fajar,

      You can use code like this

      Sub OpenWorkbooks()
          
          
          Dim arr As Variant
          Dim sFileName As String
          
          For i = 1 To 1
              sFileName = ""
              For j = 1 To 4
                  sFileName = sFileName & Sheet1.Cells(i, j) & "-"
              Next j
              ' Remove last dash
              sFileName = Left(sFileName, Len(sFileName) - 1)
              
              sFileName = "C:data" & sFileName & ".xlsx"
              
              ' Use sFilename to open file
              Dim wk As Workbook
              Set wk = Workbooks.Open(sFileName)
          Next i
      
      End Sub
      
  14. Hi Paul,

    I am using VB6 and creating a repoort using Excel.Applucatrion. Everything is fine except for certain values where I am moving a date like s = “11/07/2014” to oSheet.Range(“B6”).Value = s.
    When running the spread sheet afterwards the date shows in the cell as 07/11/2014. Most other dates are fine. It looks like months 10, 11, and 12 and days under 10 gets “converted”. Any ideas? Kind regards,

    1. Hi Henning,

      It’s hard to say without seeing the workbook or code. Select one of the cells and press Ctrl + 1. This will bring up the format cells dialog. Under the Date Category it shows the Locale. This is probably reflecting the date format that is being shown in the cell.

      Paul

  15. Hi Kelly,
    How to copy the data from a cell to all the cells till last row of the excel. where last row is the row having data in A or B column.
    I am trying to do this Paste operation in AE’s column.
    Below is my code
    Target_Path1 = “D:ARISg MainAG73_DB_TESTINGMacroAgCommsConfiguration.xlsx”
    Set Target_Workbook1 = Workbooks.Open(Target_Path1)

    Source_data1 = Source_Workbook.Sheets(1).Cells(4, 2)
    Target_Workbook1.Sheets(1).Cells(2, 31) = Source_data1
    Range(“AE2”).Select
    Selection.Copy
    Range(“AE3:AE140”).Select
    ActiveSheet.PasteSpecial

    AE140 is the manually added cell number , I wanted to add this dynamically like last row number .
    Could you please tell me how to do this?
    Thanks in advance.!!

        1. Sub FilterCashLedgerBalances()
          Dim src As Worksheet
          Dim tgt As Worksheet
          Dim filterRange As Range
          Dim copyRange As Range
          Dim lastrow As Long

          Set src = ThisWorkbook.Sheets(“Sheet1”)
          Set tgt = ThisWorkbook.Sheets(“Sheet2”)

          ‘ turn off any autofilters that are already set
          src.AutoFilterMode = False

          ‘ find the last row with data in column P
          lastrow = src.Range(“P” & src.Rows.Count).End(xlUp).Row

          ‘ the range that we are auto-filtering (all columns)
          Set filterRange = src.Range(“A1:AF” & lastrow)

          ‘ the range we want to copy (only columns we want to copy)
          ‘ in this case we are copying country from column A
          ‘ we set the range to start in row 2 to prevent copying the header
          Set copyRange = src.Range(“AE2:AE” & lastrow)

          ‘ filter range based on column AE
          filterRange.AutoFilter field:=16, Criteria1:=”Cash Filter”

          ‘ copy the visible cells to our target range
          ‘ note that you can easily find the last populated row on this sheet
          ‘ if you don’t want to over-write your previous results
          copyRange.SpecialCells(xlCellTypeVisible).Copy tgt.Range(“A2”)

          End Sub

  16. I have found code which will insert a missing year or years into a column of a sequence of years, e.g., 2011, 2012, 2014, 2015 would insert 2013 in the appropriate place – HOWEVER, the insert is based on a row, and not a single cell. The Code is simply and works but I cannot figure out how it puts the correct year in the correct cell and how NOT to have an entire row inserted in the worksheet. The years are in column L:
    Sub FindMissingYear()
    Dim i As Long, x, r As Range
    For i = Range(“L” & Rows.Count).End(xlUp).Row To 2 Step -1
    ‘Mid$() returns a string variable

    x = Mid$(Cells(i, “L”), 2) – Mid$(Cells(i – 1, “L”), 2)
    On Error Resume Next
    If x > 1 Then
    Rows(i).Resize(x – 1).Insert
    Cells(i – 1, “L”).AutoFill Cells(i – 1, “L”).Resize(x), 2
    End If
    Next
    End Sub
    Thanks for any suggestions, am frustrated to no end with this…
    Mort in Dallas

    1. Hi Mort,

      This will insert all the missing years between the first and last years.
      So if the first year is 2014 and last is 2018 it will create sequence 2014,2015,2016,2017. It only affects column L

      Sub InsertMissingYear()
      
          ' Get last row
          Dim lastRow As Long
          lastRow = Range("L" & Sheet1.Rows.Count).End(xlUp).Row
          
          ' Get the number of years by subtracting last from first
          Dim totalYears As Long
          totalYears = Range("L" & lastRow) - (Range("L1") - 1)
          
          ' Use number of years to create new range of cells and fill
          ' the series to this cell
          Range("L1").AutoFill Range("L1:L" & totalYears), xlFillSeries
          
      End Sub
      
  17. Hi Paul,

    i have manage to select a range of cells to the last non blank cell
    in the column with the following codes.

    Range(“H1″).Select
    Cells.Find(What:=”*”, After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
    xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Activate
    ActiveCell.Offset(1, -4).Range(“A1”).Select
    Range(Selection, Selection.End(xlDown)).Select

    but i need to widen the selection further to 3 columns to the left.

    could you help?

  18. I have a code that returns the last row/cell vale in a column. The problem is that it only work as long that there are more two rows. How can I get it to work with just one row/cell value.
    Dim sth as worksheet, col as new collection, c as range, numcols as long

    For each c in sth.range(“A1:D1”).cells
    col.add.application.transpose(sht.range(c, c.end(xldown))
    numcols =numcols +1
    next c

  19. The copy section did not work. “Set” was missing:
    Public Sub CopyValues()

    Dim rgCopy As range
    Set rgCopy = cnSheet1.range(“B1:B5”) ‘rest is as above in the example, still very good example!

  20. Hi Paul Kelly,
    Many thanks for this blog which I reviewed to help refresh my memory of cells and Ranges in VBA
    I have a minor, slightly academic comment:
    I have reviewed the Microsoft literature:
    Forgive me as I am learning so am probably wrong, but I am wondering if the following:-

    Range takes cell address returns multiple cells
    Cells takes row, column returns one cell

    Should be something like

    Range( ) takes cell address returns multiple cells
    Range.Item( ) takes row, column returns one cell

    I am questioning the basic idea of that the Cells Property takes row and column as arguments.

    This is my argument:
    As I understand it, Cells returns a Range object of all the cells in the object to which it is applied. This returned Range object can further have the Range Item Property applied to refer to individual cells within that Range object. ( or refer to individual cells outside that Range object also , should the original object be a Range within a worksheet )
    Fully written, we may have a code line, or part thereof, such as this
    Cells.Item(1, 2)
    As the Item property is the default Property of a Range object, we may omit the .Item. So this would be as we then typically see such a code part:
    Cells(1, 2)
    But we are never the less using the Range Item Property to refer to the cell B1. We are using Cells to return a Range object comprising of all the cells in the Object to which it is applied.

    A code line, using a variable, say Rng, for a Range object, often seen written as such
    Rng.Cells(1, 2)
    It is fully written as
    Rng.Cells.Item(1, 2)
    The .Cells is totally redundant here and can be omitted. The .Item can be omitted as previously. So we finally have this:
    Rng(1, 2)

    In the case of using .Cells to return a Range object of all the cells in a worksheet, such as this
    Ws.Cells ( Often just written as Cells )
    The following
    Ws.Cells(1, 2)
    is again fully written
    Ws.Cells.Item(1, 2)
    Here .Cells is not redundant. One could , however also do it such
    Ws.Range(“A1”).Item(1, 2)
    and again this could be simplified to
    Ws.Range(“A1”)(1, 2)

    I am simply suggesting that the Cells(row, column) is a helpful and easy way to “show” what is being done, but that strictly speaking we do not have a Cells Property with arguments of this form Cells(row, column). The Cells Property, I am suggesting, possibly in my ignorance, has no arguments. ( I am not too sure if there may be a Cells Item Property. Considering the syntax possibilities shown, I expect it would be impossible to test for )

    The above is how I see it based on the available Microsoft documentation. Just wondered if you have any comments on this?
    Thanks
    Alan Elston

    1. Hi Alan,

      As you say, Item is the actual property we are using when we use Cells(row,column). When we are writing VBA we normally don’t bother with item.

      Paul

      1. Hi Paul
        Thanks for the reply.
        I was still not too sure if it is the Range Item Property or the Cells Item Property.
        The literature does not seem to concise on if there is a Cells Item Property
        Intellisense offers Item after Cells. , and probably Excel help may suggest it, but I believe that is no Gaurantie.
        The syntay makes it impossible to be sure I think: As Cells returns a Range object, then clearly .Item( ) , ( or just ( ) ) , can be said to be that of the Range Item Property as it is applied to a Range object as returned by Cells
        Alan

  21. Hello Paul,
    I’m surprised not to see the WITH statement mentioned or the .value = .value. That said, I have a problem with it which you may be able to answer.
    I am importing two date columns from SQL. I need to format these columns as Excel dates. If they are imported into columns A and B, I use this:
    With Range(“A:B”)
    .numberformat “dd-mm-yyyy”
    .value = .value
    End With
    which works fine.
    However, if the dates are imported into A and C, and I try this:
    With Range(“A:A, C:C”)
    .numberformat “dd-mm-yyyy”
    .value = .value
    End With
    column A works fine but the whole of column C is populated with the value from cell A1. I have got around it by executing two with statements.
    The interesting thing is, if I change the SQL data type from DATE to DATEVALUE, I don’t have to use .value = .value and therefore don’t have a problem.
    I don’t necessarily have a problem that needs solving as I can get the result I need but wondered why this happens and whether there is a more elegant way of achieving my goal than two with statements.

    1. Hi Spyder,

      This occurs because your second range is two ranges whereas the first is one range.

      In VBA, You cannot only assign one range to another so in your example it takes the first range.

      Paul

  22. Hi Paul,
    Many thanks for the blog.
    I have a question how to use two Variable in define the cell.
    eg:
    Dim i As String
    Dim j As String
    Range(i &j) —- Error
    Cells(i, j) —- Error

    Thank you for your help.

    Jaydon

  23. Hi Paul,

    As a first time VBA user this blog has been amazing!

    I am using VBA to check to create a Message Box (“Please complete all fields”) when there is text in cell B9 but no text in cell Q9. I can get this to work on row 8 by using:

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Application.WorksheetFunction.IsText(Range(“C9”)) And Cells(9, 17).Value = “” Then
    MsgBox “Please Complete All Required Fields”
    Else
    End If
    End Sub

    However I want to be able to apply this to all rows 9-200 for example. If this was a formula I would just ‘drag’ the formula down all of the rows.

    Is it possible to do this in VBA? I can’t seem to solve it.

    Many thanks in advance if you can assist!!

    1. You can use a loop like this

      Dim i As Long
      For i = 9 To 200
          If Application.WorksheetFunction.IsText(Range("C" & i)) And Cells(i, 17).Value = "" Then
              MsgBox "Please Complete All Required Fields"
              Exit Sub ' so doesn't keep repeating
          End If
      Next i
      

      However, it is very slow to check all these cells each time.

      You would be better using the Change event so only do a check when a cell is changed. Then using Application.Intersect to check if cell in the given range first.

Leave a Reply

Your email address will not be published. Required fields are marked *