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 laid out in a logical order. If you prefer you can use the table of contents below to go to a section of your choice.

Topics covered include Offset property, reading values between cells, reading values to arrays and formatting cells.


A Quick Guide to Ranges and Cells

FunctionTakesReturns ExampleGives


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


Download the Code


The Webinar

If you are a member of the VBA Vault, then click on the image below to access the webinar and the associated source code.

(Note: Website members have access to the full webinar archive.)

vba ranges video



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 from a cell.
  2. Write to a cell.
  3. Change the format of a cell.

Excel has a number of methods for accessing cells such as Range, Cells and Offset.These can cause confusion as they do similar things and can lead to confusion

In this post I will tackle each one, explain why you need it and when you should use it.

Let’s start with the simplest method of accessing cells – using the Range property of the worksheet.


Important Notes

I have recently updated this article so that is uses Value2.

You may be wondering what is the difference between Value, Value2 and the default:

' Value2
Range("A1").Value2 = 56

' Value
Range("A1").Value = 56

' Default uses value
Range("A1") = 56

Using Value may truncate number if the cell is formatted as currency. If you don’t use any property then the default is Value.

It is better to use Value2 as it will always return the actual cell value(see this article from Charle Williams.)


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").Value2 = 67

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

    ' Write date to cell A3 in sheet1 of this workbook
    ThisWorkbook.Worksheets("Sheet1").Range("A3").Value2 = #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 to reference the worksheet.

code name worksheet
The following code shows the above example using the code name of the worksheet i.e. Sheet1 instead of ThisWorkbook.Worksheets(“Sheet1”).

Public Sub UsingCodeName()

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

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

    ' Write date to cell A3 in sheet1 of this workbook
    Sheet1.Range("A3").Value2 = #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
    Sheet1.Range("A1:A10").Value2 = 67

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

End Sub

You can download working examples of all the code from this post from the top of this article.

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
    Sheet1.Range("A1").Value2 = 10
    Sheet1.Cells(1, 1).Value2  = 10

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

    ' Write to E1
    Sheet1.Range("E1").Value2 = 10
    Sheet1.Cells(1, 5).Value2  = 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 to explain this with an example.

In the following code, we ask the user to specify the column number. Using Cells gives us the flexibility to use a variable number for the column.

Public Sub WriteToColumn()

    Dim UserCol As Integer
    ' Get the column number from the user
    UserCol = Application.InputBox(" Please enter the column...", Type:=1)
    ' Write text to user selected column
    Sheet1.Cells(1, UserCol).Value2 = "John Smith"

End Sub

In the above example, we are using a number for the column rather than a letter.

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 Sheet1
        ' Write 5 to Range A1:A10 using Cells property
        .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 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 Sheet1

        ' Write 5 to Range A1:A10 using Cells property
        .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 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)



You can download all the code for this post from the top of this article.

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.

VBA Offset

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: Sheet1.Range("H3").Value2 = lValue
        Case 2: Sheet1.Range("I3").Value2 = lValue
        Case 3: Sheet1.Range("J3").Value2 = lValue
        Case 4: Sheet1.Range("K3").Value2 = lValue
        Case 5: Sheet1.Range("L3").Value2 = lValue
        Case 6: Sheet1.Range("M3").Value2 = lValue
        Case 7: Sheet1.Range("N3").Value2 = 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
    Sheet1.Range("G3").Offset(, lDay).Value2 = 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
    Sheet1.Range("B2").Offset().Value2 = "Cell B2"

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

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

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

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

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

End Sub


Using the Range CurrentRegion

CurrentRegion returns a range of all the adjacent cells to the given range.

In the screenshot below you can see the two current regions. I have added borders to make the current regions clear.

VBA CurrentRegion

A row or column of blank cells signifies the end of a current region.

You can manually check the CurrentRegion in Excel by selecting a range and pressing Ctrl + Shift + *.

If we take any range of cells within the border and apply CurrentRegion, we will get back the range of cells in the entire area.

For example
Range(“B3”).CurrentRegion will return the range B3:D14
Range(“D14”).CurrentRegion will return the range B3:D14
Range(“C8:C9”).CurrentRegion will return the range B3:D14
and so on


How to Use

We get the CurrentRegion as follows

' Current region will return B3:D14 from above example
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion


Read Data Rows Only

Read through the range from the second row i.e.skipping the header row

' Current region will return B3:D14 from above example
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

' Start at row 2 - row after header
Dim i As Long
For i = 2 To rg.Rows.Count
    ' current row, column 1 of range
    Debug.Print rg.Cells(i, 1).Value2
Next i


Remove Header

Remove header row(i.e. first row) from the range. For example if range is A1:D4 this will return A2:D4

' Current region will return B3:D14 from above example
Dim rg As Range
Set rg = Sheet1.Range("B3").CurrentRegion

' Remove Header
Set rg = rg.Resize(rg.Rows.Count - 1).Offset(1)

' Start at row 1 as no header row
Dim i As Long
For i = 1 To rg.Rows.Count
    ' current row, column 1 of range
    Debug.Print rg.Cells(i, 1).Value2
Next i



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
    Sheet1.Columns(2).Font.Size = 9

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

    ' Set the font size of row 5 to 18
    Sheet1.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
    Sheet1.Range("A1:C2").Columns(2).Font.Bold = True

End Sub

You can download all the code for this post from the top of this article.

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
    Sheet1.Range("A1").Value2 = Sheet1.Range("B1").Value2

    ' Place value from B3 in sheet2 to cell A1
    Sheet1.Range("A1").Value2 = Sheet2.Range("B3").Value2

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

    ' You need to use the "Value" property to read multiple cells
    Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1:B5").Value2

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 = Sheet1.Range("B1:B5")

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

    ' You can paste to multiple destinations
    rgCopy.Copy Destination:=Sheet1.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.


Using the Range.Resize Method

When copying from one range to another using assignment(i.e. the equals sign), the destination range must be the same size as the source range.

Using the Resize function allows us to resize a range to a given number of rows and columns.

For example:

Sub ResizeExamples()
    ' Prints A1
    Debug.Print Sheet1.Range("A1").Address

    ' Prints A1:A2
    Debug.Print Sheet1.Range("A1").Resize(2, 1).Address

    ' Prints A1:A5
    Debug.Print Sheet1.Range("A1").Resize(5, 1).Address
    ' Prints A1:D1
    Debug.Print Sheet1.Range("A1").Resize(1, 4).Address
    ' Prints A1:C3
    Debug.Print Sheet1.Range("A1").Resize(3, 3).Address
End Sub

When we want to resize our destination range we can simply use the source range size.

In other words, we use the row and column count of the source range as the parameters for resizing:

Sub Resize()

    Dim rgSrc As Range, rgDest As Range
    ' Get all the data in the current region
    Set rgSrc = Sheet1.Range("A1").CurrentRegion

      ' Get the range destination
    Set rgDest = Sheet2.Range("A1")
    Set rgDest = rgDest.Resize(rgSrc.Rows.Count, rgSrc.Columns.Count)
    rgDest.Value2 = rgSrc.Value2

End Sub

We can do the resize in one line if we prefer:

Sub ResizeOneLine()

    Dim rgSrc As Range
    ' Get all the data in the current region
    Set rgSrc = Sheet1.Range("A1").CurrentRegion
    With rgSrc
        Sheet2.Range("A1").Resize(.Rows.Count, .Columns.Count).Value2 = .Value2
    End With
End Sub


Reading Values to variables

We looked at 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 UseVariables()

    ' Create
    Dim number As Long

    ' Read number from cell
    number = Sheet1.Range("A1").Value2

    ' Add 1 to value
    number = number + 1

    ' Write new value to cell
    Sheet1.Range("A2").Value2 = number

End Sub

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

Public Sub UseVariableText()

    ' Declare a variable of type string
    Dim text As String

    ' Read value from cell
    text = Sheet1.Range("A1").Value2

    ' Write value to cell
    Sheet1.Range("A2").Value2 = text

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
    Sheet1.Range("A1:B10").Value2 = 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.

Note: We normally use Range.Copy when we want to copy formats, formulas, validation. If we want to copy values it is not the most efficient method.
I have written a complete guide to copying data in Excel VBA here.

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


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").Value2 = Range("A1:Z1").Value2

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 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").Value2

    ' Do something with array here

    ' Write the 26 values to the third row
    Range("A3:Z3").Value2 = 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 Sheet1.Range("A1:A10,A20")
        ' Print address of cells that are negative
        If rg.Value < 0 Then
            Debug.Print rg.Address + " is negative."
        End If

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

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

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)



  1. Hi Paul,
    I am new at excel macros and I’ve stumbled on looping issue. I have a macro that does what I want but it requires certain guessing
    on a user part and I don’t like the guessing.
    I have formulas in two columns D7 (=E6-$D$4) & E6 (=D6-(ABS(D6)^0.5)) starting row 6.
    100, $D$4=01 and H2=20 are manual entries and H2 is guessed number of iterations.

    D E

    6 100 90
    7 89.9 80.41843895
    8 80.31843895 71.35638344
    9 71.25638344 62.81503382
    10 62.71503382 54.79575141
    11 54.69575141 47.30009381
    12 47.20009381 40.32986136
    13 40.22986136 33.88715994
    14 33.78715994 27.97448758
    15 27.87448758 22.59485809
    16 22.49485809 17.75198363
    17 17.65198363 13.45055725
    18 13.35055725 9.696715815
    19 9.596715815 6.498859167
    20 6.398859167 3.869262526
    21 3.769262526 1.82780366
    22 1.72780366 0.413344205
    23 0.313344205 -0.24642736
    24 -0.34642736 -0.935008162
    25 -1.035008162 -2.05236167
    26 -2.15236167 -3.619454602
    27 -3.719454602 -5.648043361

    I want to loop through the formulas until value in one column changes to negative and and then macro stops instead as running
    predefined number of times to eliminate situation when guessed number of iterations will be too small and negative value currently in E23 won’t be reached.
    However when I eliminate H20 and I’m trying to use loop with condition to loop until first negative value in column E is reached, macro crushes.

    My current code is as below and I’d really appreciate your comments, I can’t find a suitable example online.

    Best regards,


    Sub AddRowFormula()
    Dim n As Range, rng As Range, rng1 As Range
    ‘ # of iterations
    Set n = Range(“H2”)
    ‘ cell where formulas start
    Set rng = Range(“D7”)
    Range(rng.Offset(1, 0), rng.Offset(3, 0)).EntireRow.Insert
    Range(rng, rng.End(xlToRight)).Copy
    Range(rng, rng.Offset(n, 0)).PasteSpecial
    Set rng = rng.Offset(n + 1, 0)
    If rng = “” Then
    GoTo line1
    GoTo line2
    End If
    Application.CutCopyMode = False
    MsgBox “Macro completed”
    End Sub

    1. Hi Adam,

      I am not 100% clear on what you are trying to achieve with your macro.

      “I want to loop through the formulas until value in one column changes to negative and and then macro stops”

      You haven’t said why you are copying and pasting and what you are trying to achieve.


      1. Hi Paul,
        Thank you for replying and my apology for not being clear about my issue.
        The goal is to run the calculations until a break point between positive and negative values in column E is reached, in this case:
        E22 = 0.413344205
        E23 = -0.24642736
        I want the calculations to stop when the first negative number will be obtained – in this case E23.
        Right now the macro I am using is working based on fixed number of calculations stated in H2 and equals 20 and the number of iterations is chosen arbitrarily, simply speaking just a guess. I want to eliminate the guess work and keep copying the formulas down until first negative value in column E will show up. I’m not concerned with the number of iterations, if it will take three iterations to get first negative or it will take few hundreds or even few thousands. As long as I’ll get the break point I’ll be happy:-)
        I hope this makes sense but if not I’ll try to make it clearer.
        Best Regards,

        1. This should do the trick

          Sub GetBreak()
              Dim bFound As Boolean
              bFound = False
              Dim row As Long
              row = 7
                  Sheet1.Range("D" & row & ":E" & row).Copy _
                              Sheet1.Range("D" & row + 1 & ":E" & row + 1)
                  ' Check for negative value
                  If Sheet1.Range("D" & row + 1).Value < 0 Then
                      bFound = True
                  End If
                  ' Move to next row
                  row = row + 1
              Loop Until bFound = True
          End Sub
          1. Thank you very much Paul.
            I works perfectly the way I wanted:-)
            It is also a great example because it only works in specific range without inserting extra rows which could mess with other parts of the sheet.

            Best Regards,


  2. HI Paul,

    Great tutorials, thanks!!

    When I try and run:

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

    I get two problems, one my excel doesn’t like the number 1 as the start of a variable.
    the other is I get a ” run-time error 1004: Application-defined or object-defined error”
    when I try to execute the code

    1. Update: changing “Range(“A1”) to Cells(1,1) did the trick!

      Sub WriteToFirstBlankCell()

      Dim OneLastCol As Integer
      ‘OneLastCol = cnSheet1.Range(“A1”).End(xlToRight).Column
      OneLastCol = cnSheet1.Cells(1, 1).End(xlToRight).Column

      cnSheet1.Cells(1, OneLastCol + 1) = “John Smith”
      ‘ cnSheet1.Cells(1, OneastCol + 1) = “John Smith”

      End Sub

      Kind Regards,

      1. Hi Nick,

        It is the letter l in front of LastCol rather than the number one:-)

        Range(“A1”) will work fine. Cells(1,1) is essentially the same thing.

        If you only have text in cell A1 in the first row then this error occurs.

        The following line should prevent this error(add it before the last line with “John Smith”

        lLastCol = IIf(lLastCol = cnSheet1.Columns.Count, 1, lLastCol)


        1. Great, Thanks Paul 🙂

          It seems the Cells(1,1) reference works after a fashion with a blank worksheet – it just sticks “John Smith” right at the end of the sheet

          Kind Regards,


  3. Hi Paul,

    In the example “Reading Values from one Cell to another” you have the example:
    “‘ Will not work – You cannot read from multiple cells
    cnSheet1.Range(“A1:A5”) = cnSheet1.Range(“B1:B5″)”

    If you add .value to the end of the code you can then duplicate the range B1:B5
    I’m not sure why this seems to make the difference – do you mind explaining?

    Kind Regards,


    1. Hi Nick,

      I changed that example slightly to use Value. Before otherwise it is a bit misleading.

      Value for a single cell is a single value.
      Value for multiple cells is a 2D array.

      You cannot use the default with multiple – only with single. I’m not sure why this is the case.


      1. Hi Paul,
        Thanks – great instructions, I’ve learned a whole load about VBA from your site already!



  4. Hi Paul,

    I need your help. Here’s my problem:
    A1 Contains a drop-down list. B1 will populate (via drop down list also) based on selected item from A1.

    Say if select “Tissue” from A1, then I can only see different brand of tissues from B1
    If I select “Fruit” from A1, then I can only see fruit selections from B1
    I will not be allowed to fill-out B1 unless I select something from A1.

    My dilemma now is that If both cells are already filled-out, I can still go back to A1 and change it. It will accept the change made and will not prompt an error even if B1 was not changed. In effect the data in A1 and B1 are now misaligned. Can you help me with a code where it will prevent any changes in A1 if the data in B1 do not corresponds with A1?

    Thanks and appreciate any help you can provide.

  5. Hello Paul,

    Compliments on such a clearly-written tutorial! Almost as impressive is the extensive comments attached to it! With apologies, I haven’t read through all of them to see if anyone else has the same question.

    My question is whether Range().Offset starts offsets at zero or one. In the section “The Offset Property of Range”, the DayOffSet() example function seems to take lDay=1 as meaning no offset, lDay=2 as an offset of one, and so on. However the following UsingOffset() example seems to take 1 as an offset of one. Am I missing something?

    In any case, thanks for such a well-written tutorial!
    Cheers, Angus

    1. Offset starts at 1.
      For column 0 is not offset, -1 is one column to the left, 1 is one column to the right.

      1. Hello Paul,

        I am comparing the SetValueSelect() and DayOffSet() subroutines. When lDay = 1, SetValueSelect() executes

        Case 1: cnSheet1.Range(“G3”) = lValue

        which puts lValue in cell G3. But when DayOffSet() executes

        cnSheet1.Range(“G3”).Offset(, lDay) = lValue

        doesn’t that put lValue in cell H3?

        Cheers, Angus

        1. Hi Angus,

          I see what you mean. The SetValueSelect sub should indeed start at H3.

          I have updated the example.

          Thanks for pointing that out.


  6. Hello Paul,

    I am having some trouble in understand the cell traverse pattern of FOR loop.
    The code is {i,j,k as integer: g1b double}
    For k = 1 To 7
    For j = 1 To 7
    For j = 1 To 6
    ThisWorkbook.Sheets(“Consumption”).Cells( 11 * i + k – 4, j +2 ).Value

    Next i
    ThisWorkbook.Sheets(“Emissions Calculation”).Cells(8 + k, j + 13).Value = g1b
    Next j
    Next k
    end sub

    I understand that “i” will go 11 multiples in the sheet, but i did not understand [ + k – 4 ] part.
    Glad if you could help me

    1. Hi Anshuman

      The third For loop should be For i instead of For j.

      The loops work like this

      i = 6 then

      and so on until

  7. I have a combo box that contains a list of worksheet names. the user will select the appropriate sheet in the combo box and then when another button is selected I want it to display a listing of all information in column “A” of the previously selected sheet

    1. Hi Randy,

      You can do it like this

          ' Get the worksheet from the name in the combobox
          Dim sh As Worksheet
          Set sh = ThisWorkbook.Worksheets(Trim(Sheet1.ComboBox1.Value))
          ' Get the last row
          Dim lastrow As Long
          lastrow = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row
          ' read through the cells
          Dim i As Long
          For i = 1 To lastrow
              ' Print the value of all the cells
              Debug.Print sh.Range("A" & i)
          Next i
  8. Hi Paul,

    I am trying to do a time tracker and I have come up with the simplest vba along with an inserted start/stop button. I was able to do starttimestamp when I press the button on A1 then the active cell will now go to B1 then hit the button for endtime stamp again. It works fine however what I wanted to do next was to put the active cell after B1 this time on A2 for start time then B2 for end, and then A3 then B3 and so on. Could you please edit and maybe give a little hint on how to do this. Thank you so much Paul!

    Sub EnterCurrentTime()

    ‘ EnterCurrentTime Macro
    ‘ This macro enters the current time into the active cell
    ActiveCell.Value = Now()
    ActiveCell.Offset(0, 1).Select
    End Sub

  9. Hi Paul ad thank you very much for the great info.
    How do I select a range of cells (say a table, for example with a fixed number of columns and a variable number of rows), making sure that my selection captures every time all the non empty rows?
    In other words, how do I specify the parameters of a range by using variables and not constants (such as startingcell:endingcell instead of “B1:C3”)?
    Kindly let me know.
    Best Regards

  10. Hi Paul,

    I earnestly need your help.
    I have a source file holding ongong projects names in column B with their respective status in adjacent rows. Hence each project has its status adjacent to it in the same row but under columns C,D,E,F etc. Also their is possibility of new projects to be added to the source in the same structure above.
    I need a separate automated workbook called ” QUICK report “to automatically extract these Project with their statuses into specific cells and always check for newly added project/s to likewise extract into specific Cells. The extraction should stop at any blank row.

  11. Hi,
    I have an macro code to read cells from an xlsx file and dump into an csv in an automated fashion. Now the issues is some of the data is wrongly dumped in csv due to the xls issues to show all data greater than 15 chars .
    Actual data 4142900101000010 becomes 4.1429E+15 , as is dumped in csv .

    Any solution to this problem.


    1. Sample code for fetching cells

      For n = data_start To Data_count

      For p = 1 To tab_col_cnt
      ‘MsgBox “csvop begin :” & csvop
      If data_bnk = “N” Then
      If p = 1 Then
      ‘MsgBox “Check1”
      csvop = wkb.Worksheets(i).Cells(n, p)
      ‘MsgBox wkb.Worksheets(i).Cells(n, p)
      ‘MsgBox “csvop :” & csvop
      csvfileout.Write csvop
      ‘MsgBox “Check2”
      ‘MsgBox wkb.Worksheets(i).Cells(n, p)
      csvfileout.Write “,”
      csvop = wkb.Worksheets(i).Cells(n, p)
      ‘MsgBox “csvop :” & csvop
      csvfileout.Write csvop
      End If
      End If
      Next p
      csvfileout.Writeline “”
      Next n

  12. Hello!!!
    Please I have a doubt
    Here I want to copy all the A column of WS1 not found in WS2 column A, in the W3 column A
    Thanks to assist!

    Sub galopin()
    Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet, ws4 As Worksheet, ws5 As Worksheet, i1, i2, i3, k, kk, z
    Set ws1 = Worksheets(1)
    Set ws2 = Worksheets(2)
    Set ws3 = Worksheets(3)

    ‘declaration des feuilles d’entree
    i1 = ws1.Range(“A1”).End(4).Row
    i2 = ws2.Range(“A1”).End(4).Row

    With ws1
    For k = 1 To i1
    z = .Range(“A” & k).Value

    For kk = 1 To i2
    ‘ If z ws2.Range(“A” & kk).Value Then
    ‘ws3.Range(“A” & i3 + 1) = z

    ‘Here I want to copy all the A column of WS1 not found in WS2 column A, in the W3 column A

    ‘z = ws1.Range(“A” & k).Value
    If Not (ws2.Range(“A2:A65536”).Find(z) Is Nothing) Then
    ws3.Range(“A” & i3 + 1).Value = z

    i3 = i3 + 1
    End If

    End With
    End Sub

  13. Hi, Am not able to solve the below problem.
    In the 1st Row there are 6 numbers i.e. A1=10, B1=19, C1=22, D1-35, E1=45
    In the 2nd Row there are 6 numbers i.e. A1=9, B1=14, C1=28, D1-38, E1=48

    What I would like is if I have to find 2 numbers ie 19 and 35 to be cell highlighted with green color and the formula or vb excel to highlight the cells that matches 19 and 35.

  14. Dear Paul
    In the following example related to range, I cannot define the array elements individually::
    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

    1. Hi Ahmad,

      I’m not sure what you mean by “define individually”.

      Can you show me the line of code you are having trouble with?

  15. Good day, why is this piece of VBA code not running? I need help please.
    Sub UniformRandGen()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Dim rCt As Integer, rMax As Integer
    rMax = 100
    ReDim uArray(1 To rMax, 0)


    For rCt = 1 To rMax
    uArray(rCt, 0) = Rnd(-rCt)
    Next rCt

    Range(“$C$5:$C$104”) = uArray
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    End Sub

    1. What do you mean by not working?

      I notice that you do not have a worksheet specified before Range.

      This means it will write the array to whichever worksheet is active.

  16. Hi, I am quite new to VBA and trying to create an excel template that uses VBA to change a path and automatically gather data from other workbooks. Basically creating a master document to store the information.

    At the moment I am using the following code:

    Sub CallOtherWB()

    Dim JobNumber As String

    JobNumber = Range(“C4”).Value

    With Range(“D4”)
    .Formula = “=’Y:\Public\QA Other\Scorecards\Copy of Scorecard v0.6 ” &
    JobNumber & “.xlsm’!Total”
    End With

    End Sub
    However I haven’t figured out how to make the range go through C4:C50 and grab the data entered there to edit (“=’Y:\Public\QA Other\Scorecards\Copy of Scorecard v0.6 ” & JobNumber & “.xlsm’!Total”) which would go in D4:D50.

    I searched through other questions and tried to do a sort of loop but was not able to understand how to make the range work. To summarize I am using that code to enter the information in the C column and for that information to replace the “JobNumber” part in the D column so that it has the correct file name.

    I am trying to get the information that I enter in the C column of the master workbook to replace the job number part of the path which is in the D column of the master workbook. The cell is it referencing(Total) has a number which I need to use in the master book and i need it to be updated as we work in the other workbooks. This seems to help me update all the D column but with the same value in C4 when I need it to update as C5 to D5, C6 to D6 and so on

    Please let me know if I need to clarify this further and thanks in advance for the help.

    1. Hi Josh,

      this should help

      Sub ReadData()
          ' Get the range of cells to read
          Dim rg As Range
          Set rg = Sheet1.Range("C4:C50")
          Dim i As Long, JobNumber As String
          ' read through each of the cells in the range
          For i = 1 To rg.Rows.Count
              JobNumber = rg.Cells(i, 1).Value
              ' move over one column using offset
              rg.Offset(0, 1).Formula = "Y:\Public\QA Other\Scorecards\Copy of Scorecard v0.6 " & "" & JobNumber & ".xlsm!Total"
          Next i
      End Sub
  17. Hi Paul
    Could you please assist me in finding whats wrong in my code below. While executing the codes below it encountered ‘runtime error 5: Invalid procedure call or argument’
    Sub max()
    Dim rng As Range, rngee As Range
    Dim max1 As Double, max2 As Double
    Dim monthly_salary As Range
    Dim lastrow As Long
    Dim i As Integer
    lastrow = ThisWorkbook.Sheets(“Bonus Calculation Template”).Cells(Rows.Count, 2).End(xlUp).Row
    For i = 6 To lastrow
    Set monthly_salary = Range(“F” & i)
    If monthly_salary <= 15000 Then
    Set rng = Range("I" & i)
    Set rngee = Range("I" & i)
    End If
    max1 = Application.WorksheetFunction.max(rng)
    max2 = Application.WorksheetFunction.max(rngee)
    Next i
    Range("L1").Value = max1
    Range("M1").Value = max2
    End Sub

    1. One of the variables rng\rngee will be Nothing because only one is set the first time the code reaches the WorksheetFunction lines.

      You cannot pass a variable of Nothing to a worksheet function because it is expecting a range.

  18. Hi Paul,

    I am new to vba codes and macro.
    I want to use vba codes and macro to my excel sheet to reduce the time of calculating manually.
    I need to know that how can I take input numerical values from any cell in active sheet, perform calculation using formula and show output to any cell in active sheet.
    Will you please help me out.

  19. Hi Paul,
    Could you help me correct my code below? It mostly works like I want it to, however I am having problems with the insertion of the new row. I have multiple charts on the sheet, so I want the new row insert to only be over a specified numbers of columns. The range set from A to K is the width of my first chart. When the code identifies the YTD input, I want it to add a row above for the width of the chart. As it is, the code adds a row to the entire sheet which impact the other charts. Can you fix this please?
    Sub Sheet1()
    Dim N As Long
    Dim r As Range
    Dim rng As Range
    Dim d As Date
    Dim C As Variant
    Dim FirstRow As Integer

    With Worksheets(1).Range(“A1:K20”)
    Set C = .Find(“YTD”, LookIn:=xlValues)
    If Not C Is Nothing Then
    FirstRow = C.Row + 1

    Set C = .FindNext(C)
    Loop While Not C Is Nothing And C.Row FirstRow
    End If
    End With

    ‘N = Cells(Rows.Count, “A”).End(xlUp).Row
    Set rng = Range(“A1:”)

    For Each r In rng
    If IsDate(r.Value) Then
    d = r.Value
    If d < Date Then
    r.Value = DateSerial(year(d) + 1, Month(d), dAY(d))
    End If
    End If
    Next r
    End Sub

  20. Hi,
    I’m implementing RegEx validations for the column values in the given range.
    Here is my code:
    Dim rangeCustomRule10 As range
    Set rangeCustomRule10 = range(“K2:K100000, M2:M100000, O2:100000”)

    I’m getting below error message at rum time.
    Run-time error ‘1004’
    Method ‘Range’ of object ‘_Worksheet’ failed

    If I remove the third column(O2:100000), Its working perfectly.
    Any idea to solve this issue?
    Thanks in Advance.

    1. The Issue is solved. Its a typo error. range(“K2:K100000, M2:M100000, O2:100000”) should be range(“K2:K100000, M2:M100000, O2:O100000”).

      Sorry for posting my blunder mistake.

  21. I’m having a problem with a macro it overflow or something. I’m adding a hour to a data but adding the cells via macro and around cell 150 it blow up. If i delete the lines trout 140 to 160 it keep blowing at cell 150. I’m adding it whit:

    lastRow2 = Excel.Worksheets(“FPYNormas”).UsedRange.Rows.Count
    For m = 2 To lastRow2
    Set Report = Excel.Worksheets(Excel.Worksheets(“FPYNormas”).Cells(m, 1).Value)
    lastRow = Report.UsedRange.Rows.Count
    For i = 2 To lastRow
    Report.Cells(i, 8).NumberFormat = “dd-mm-yyyy h:mm:ss;@”
    Report.Cells(i, 8).Value = Report.Cells(i, 7).Value + Report.Cells(i, 6).Value ‘<— Blow up on this line
    Next i

    Column 7 is the hour, Column 6 is date, Column 8 is the sume

  22. Hi paul, When i write below code on my Excel, it is showing error as Heighlighting “Public Sub UsingCodeName()”. Am unable to find the mistake. Can you please help.

    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

  23. Hi Paul, I have written a macro that uses cell values as lines in the body of an email. It works but I need to modify the macro to work in conjunction with a second macro that hides or unhides lines depending on the value entered into a cell. I only want the lines visible in Excel to be emailed. Here is what I have now, any suggestions?

    Sub Email_ActiveSheet_As_PDF()

    ‘Do not forget to change the email ID
    ‘before running this code

    Dim OlApp As Object
    Dim olMail As Object
    Dim cell As Range
    Dim emailTo As String
    Dim NewMail As Object
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim FileFullPath As String

    With Application
    .ScreenUpdating = False
    .EnableEvents = False
    End With

    ‘ Temporary file path where pdf
    ‘ file will be saved before
    ‘ sending it in email by attaching it.

    TempFilePath = Environ$(“temp”) & “\”

    ‘ Now append a date and time stamp
    ‘ in your pdf file name. Naming convention
    ‘ can be changed based on your requirement.

    TempFileName = “Order Confirmation” & “.pdf”

    ‘Complete path of the file where it is saved
    FileFullPath = TempFilePath & TempFileName

    ‘Now open a new mail

    Set OlApp = CreateObject(“Outlook.Application”)

    If OlApp Is Nothing Then
    Set OlApp = CreateObject(“Outlook.Application”)
    End If
    On Error GoTo 0

    emailTo = “”
    For Each cell In Range(“N25:P25”)
    If cell.Value “” Then emailTo = emailTo & cell.Value & “; ”

    emailCc = “”
    For Each cell In Range(“N26:T26”)
    If cell.Value 0 Then emailCc = emailCc & cell.Value & “; ”

    EmailSubject = “”
    For Each cell In Range(“N24:V24”)
    If cell.Value “” Then EmailSubject = cell.Value
    For Each cell In Range(“N6”)
    If cell.Value “” Then EmailSubject = EmailSubject & ” Order# ” & cell.Value

    Set olMail = OlApp.createitem(0)
    Set OutApp = CreateObject(“Outlook.Application”)
    Set OutMail = OutApp.createitem(0)

    msg1 = msg1 & Range(“A1”).Value & “”
    msg1 = msg1 & Range(“A2”).Value & “”
    msg1 = msg1 & Range(“A3”).Value & “”
    msg1 = msg1 & Range(“A4”).Value & “”
    msg1 = msg1 & Range(“A5”).Value & “”
    msg1 = msg1 & Range(“A6”).Value & “”
    msg1 = msg1 & Range(“A7”).Value & “”
    msg1 = msg1 & Range(“A8”).Value & “”
    msg1 = msg1 & Range(“A9”).Value & “”
    msg1 = msg1 & Range(“A10”).Value & “”
    msg1 = msg1 & Range(“A11”).Value & “”
    msg1 = msg1 & Range(“A12”).Value & “”
    msg1 = msg1 & Range(“A13”).Value & “”
    msg1 = msg1 & Range(“A14”).Value & “”
    msg1 = msg1 & Range(“A15”).Value & “”
    msg1 = msg1 & Range(“A16”).Value & “”
    msg1 = msg1 & Range(“A17”).Value & “”
    msg1 = msg1 & Range(“A18”).Value & “”
    msg1 = msg1 & Range(“A19”).Value & “”
    msg1 = msg1 & Range(“A20”).Value & “”
    msg1 = msg1 & Range(“A21”).Value & “”
    msg1 = msg1 & Range(“A21”).Value & “”
    msg1 = msg1 & Range(“A22”).Value & “”
    msg1 = msg1 & Range(“A23”).Value & “”
    msg1 = msg1 & Range(“A24”).Value & “”
    msg1 = msg1 & Range(“A25”).Value & “”

    With olMail
    .To = emailTo
    .Cc = emailCc
    .Subject = EmailSubject
    .HTMLBody = msg1
    ‘add the image in hidden manner, position at 0 will make it hidden
    .Attachments.Add “C:\Users\viglionej\desktop\signature2.png”, olByValue, 0

    ‘Now add it to the Html body using image name
    ‘change the src property to ‘cid:your image filename’
    ‘it will be changed to the correct cid when its sent.
    .HTMLBody = .HTMLBody & “”
    End With
    On Error GoTo 0

    End Sub

  24. HI Paul,

    I have a question on applying property on filtered range. when applying cells.locked = true or false why doesn’t the hidden cells remains unchanged. Especially in Tables.

    1. Is there any solution to apply properties to hidden ranges. Even the array doesn’t apply in filtered range. we need to remove the filter and apply the array values to cells. Only then the values are getting populated in cells correctly.

  25. Is there any way we could create user defined property to an object like cells so that we can find out a way to apply the locked property = false to all the entire range of cells (including the hidden range).

  26. Hi Paul, I have a question, I’m trying to loop using FOR and IF, I need to check two cells with different conditions, but I always get the same error message no matter what I do, the code goes this way, I’m not sure if I’m missing something, would you check it? how can i fix it? thanks for your help

    Dim i As Integer
    Dim A As Integer

    A = Worksheets(“Datos”).Range(“D13”).End(xlDown).Rows.Count

    With ThisWorkbook.Sheets(“Datos”)

    For i = 13 To A

    if Range(“B” & i).Value=0 and Range(“D” & i).Value>0

    1. Both uses of Range should have a full stop before them

      .Range(“B” & i)

      This means they are part of the object in the With statement.

      Without the With statement it would be

      ThisWorkbook.Sheets(“Datos”).Range(“B” & i)

      Using the With statement it is
      With ThisWorkbook.Sheets(“Datos”)
      .Range(“B” & i)
      End With

  27. Hi
    I would like to know if can make a macro for copy multiple columns (numbers) into one cell?
    Example: copy A1:C10 cells and paste in D1 cell whit spaces between characters ( numbers )
    Many thanks

  28. I’ve been putting in an earnest effort to learn this but perhaps VBA doesn’t have a solution for me. I have just 1 column of data. It’s about 20 sets of variably sized data (with headers) seperated by blank rows.


    I’d like to sort (ascending) each data set separately, CurrentRegion.Sort works great for the first one, but how do I target the next set, then the next, to the nth set until it ends. I’ll keep digging, but I’m coming up pretty dry. I could pull it out with powershell slap it into shape and paste it back in, but that’d be too easy. I want to learn VBA.

    1. Hi Jay,

      You can find the ranges like this

      ' get the blank cells in the column
      Dim rg As Range
      Set rg = Sheet1.Columns(1).SpecialCells(xlCellTypeBlanks)
      Dim arr As Variant, cell As Variant, blankcells As String
      blankcells = "A1" & "," & rg.Address
      ' Put all the blank cells in an array so we can read through it
      arr = Split(blankcells, ",")
      For Each cell In arr
          ' Get the current region of the cell after the blank cell
          Set rgcurr = Sheet1.Range(cell).Offset(1).CurrentRegion
          ' Print the range to the Immediate Window
          Debug.Print rgcurr.Address
      Next cell
      1. You are Frustratingly good. Your way works precisely. And for your entertainment, Here’s the bohemoth I conjured up trying to fumble it together myself.

        Sub SearchAndSort()
        ‘ Le Macron

        Dim actSheet As Worksheet
        Dim upper, lower As Integer
        Dim tempString As String
        Dim selectedArea As Range
        Dim element As Variant

        Dim sLines(1 To 19) As String
        sLines(1) = “Authorized Stored Procedures and Functions:”
        sLines(2) = “Authorized Permissions for Listed Folder: C:\awesome\”
        sLines(3) = “Authorized Permissions for Listed Folder: E:\backup\”
        sLines(4) = “Authorized Permissions for Listed Folder: E:\Popnlock”
        sLines(5) = “Authorized Permissions for Listed Folder: E:\johnsnow”
        sLines(6) = “Authorized Permissions for Listed Folder: E:\nedstark”
        sLines(7) = “Authorized Permissions for Listed Folder: e:\tothekingintheNorth\”
        sLines(8) = “Authorized Permissions for Listed Folder: e:\cripplesbastardsandbrokenthings\)”
        sLines(9) = “Authorized Permissions for Listed Folder: e:\MSSQL\Binn)”
        sLines(11) = “Login and Permissions are authorized:”
        sLines(12) = “Authorized user-defined roles:”
        sLines(13) = “Direct user assignments to server permissions and user-defined server roles”
        sLines(14) = “Authorized Logins And Permissions”
        sLines(15) = “Authorized stored procedures and jobs”
        sLines(16) = “SQL Server Account Authorized to own database objects”
        sLines(17) = “Server Authentication Mode”
        sLines(19) = “Optional features SQL Server Integrated Services (SSIS):”
        sLines(18) = “Organizational defined numer of sessions”

        Set actSheet = Application.Worksheets(“APPENDIX B”)
        Set selectedArea = Selection

        For Each element In sLines

        Cells.Find(What:=element, After:= _
        ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).CurrentRegion.Select
        Set selectedArea = Selection
        selectedArea.Sort Key1:=Range(“A1”), Order1:=xlAscending, Header:=xlYes

        Next element

        End Sub

        And yea, it worked… until we inevitably add data sets. Thank You so much for the help!!!

Leave a Reply

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