Excel vba get row from range

Содержание

  1. Refer to Rows and Columns
  2. About the Contributor
  3. Support and feedback
  4. Range.Rows property (Excel)
  5. Syntax
  6. Remarks
  7. Example
  8. Support and feedback
  9. Свойство Range.Rows (Excel)
  10. Синтаксис
  11. Замечания
  12. Пример
  13. Поддержка и обратная связь
  14. Range object (Excel)
  15. Remarks
  16. Example
  17. Methods
  18. Properties
  19. See also
  20. Support and feedback

Refer to Rows and Columns

Use the Rows property or the Columns property to work with entire rows or columns. These properties return a Range object that represents a range of cells. In the following example, Rows(1) returns row one on Sheet1. The Bold property of the Font object for the range is then set to True.

The following table illustrates some row and column references using the Rows and Columns properties.

Reference Meaning
Rows(1) Row one
Rows All the rows on the worksheet
Columns(1) Column one
Columns(«A») Column one
Columns All the columns on the worksheet

To work with several rows or columns at the same time, create an object variable and use the Union method, combining multiple calls to the Rows or Columns property. The following example changes the format of rows one, three, and five on worksheet one in the active workbook to bold.

Sample code provided by: Dennis Wallentin, VSTO & .NET & Excel This example deletes the empty rows from a selected range.

This example deletes the empty columns from a selected range.

About the Contributor

Dennis Wallentin is the author of VSTO & .NET & Excel, a blog that focuses on .NET Framework solutions for Excel and Excel Services. Dennis has been developing Excel solutions for over 20 years and is also the coauthor of «Professional Excel Development: The Definitive Guide to Developing Applications Using Microsoft Excel, VBA and .NET (2nd Edition).»

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Range.Rows property (Excel)

Returns a Range object that represents the rows in the specified range.

Syntax

expression.Rows

expression A variable that represents a Range object.

To return a single row, use the Item property or equivalently include an index in parentheses. For example, both Selection.Rows(1) and Selection.Rows.Item(1) return the first row of the selection.

When applied to a Range object that is a multiple selection, this property returns rows from only the first area of the range. For example, if the Range object someRange has two areas—A1:B2 and C3:D4—, someRange.Rows.Count returns 2, not 4. To use this property on a range that may contain a multiple selection, test Areas.Count to determine whether the range is a multiple selection. If it is, loop over each area in the range, as shown in the third example.

The returned range might be outside the specified range. For example, Range(«A1:B2»).Rows(5) returns cells A5:B5. For more information, see the Item property.

Using the Rows property without an object qualifier is equivalent to using ActiveSheet.Rows. For more information, see the Worksheet.Rows property.

Example

This example deletes the range B5:Z5 on Sheet1 of the active workbook.

This example deletes rows in the current region on worksheet one of the active workbook where the value of cell one in the row is the same as the value of cell one in the previous row.

This example displays the number of rows in the selection on Sheet1. If more than one area is selected, the example loops through each area.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Свойство Range.Rows (Excel)

Возвращает объект Range , представляющий строки в указанном диапазоне.

Синтаксис

expression. Строк

выражение: переменная, представляющая объект Range.

Замечания

Чтобы вернуть одну строку, используйте свойство Item или аналогично включите индекс в круглые скобки. Например, и Selection.Rows(1) Selection.Rows.Item(1) возвращают первую строку выделенного фрагмента.

При применении к объекту Range , который является множественным выделением, это свойство возвращает строки только из первой области диапазона. Например, если объект someRange Range имеет две области — A1:B2 и C3:D4, someRange.Rows.Count возвращает значение 2, а не 4. Чтобы использовать это свойство в диапазоне, который может содержать несколько выделенных элементов, проверьте Areas.Count , чтобы определить, является ли диапазон множественным выбором. Если это так, выполните цикл по каждой области диапазона, как показано в третьем примере.

Возвращаемый диапазон может находиться за пределами указанного диапазона. Например, Range(«A1:B2»).Rows(5) возвращает ячейки A5:B5. Дополнительные сведения см. в разделе Свойство Item .

Использование свойства Rows без квалификатора объекта эквивалентно использованию ActiveSheet.Rows. Дополнительные сведения см. в свойстве Worksheet.Rows .

Пример

В этом примере удаляется диапазон B5:Z5 на листе 1 активной книги.

В этом примере строки в текущем регионе удаляются на листе одной из активных книг, где значение ячейки в строке совпадает со значением ячейки в предыдущей строке.

В этом примере отображается количество строк в выделенном фрагменте на листе Sheet1. Если выбрано несколько областей, в примере выполняется цикл по каждой области.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Range object (Excel)

Represents a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3D range.

Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.

The default member of Range forwards calls without parameters to the Value property and calls with parameters to the Item member. Accordingly, someRange = someOtherRange is equivalent to someRange.Value = someOtherRange.Value , someRange(1) to someRange.Item(1) and someRange(1,1) to someRange.Item(1,1) .

The following properties and methods for returning a Range object are described in the Example section:

  • Range and Cells properties of the Worksheet object
  • Range and Cells properties of the Range object
  • Rows and Columns properties of the Worksheet object
  • Rows and Columns properties of the Range object
  • Offset property of the Range object
  • Union method of the Application object

Example

Use Range (arg), where arg names the range, to return a Range object that represents a single cell or a range of cells. The following example places the value of cell A1 in cell A5.

The following example fills the range A1:H8 with random numbers by setting the formula for each cell in the range. When it’s used without an object qualifier (an object to the left of the period), the Range property returns a range on the active sheet. If the active sheet isn’t a worksheet, the method fails.

Use the Activate method of the Worksheet object to activate a worksheet before you use the Range property without an explicit object qualifier.

The following example clears the contents of the range named Criteria.

If you use a text argument for the range address, you must specify the address in A1-style notation (you cannot use R1C1-style notation).

Use Cells on a worksheet to obtain a range consisting all single cells on the worksheet. You can access single cells via Item(row, column), where row is the row index and column is the column index. Item can be omitted since the call is forwarded to it by the default member of Range. The following example sets the value of cell A1 to 24 and of cell B1 to 42 on the first sheet of the active workbook.

The following example sets the formula for cell A2.

Although you can also use Range(«A1») to return cell A1, there may be times when the Cells property is more convenient because you can use a variable for the row or column. The following example creates column and row headings on Sheet1. Be aware that after the worksheet has been activated, the Cells property can be used without an explicit sheet declaration (it returns a cell on the active sheet).

Although you could use Visual Basic string functions to alter A1-style references, it is easier (and better programming practice) to use the Cells(1, 1) notation.

Use_expression_.Cells, where expression is an expression that returns a Range object, to obtain a range with the same address consisting of single cells. On such a range, you access single cells via Item(row, column), where are relative to the upper-left corner of the first area of the range. Item can be omitted since the call is forwarded to it by the default member of Range. The following example sets the formula for cell C5 and D5 of the first sheet of the active workbook.

Use Range (cell1, cell2), where cell1 and cell2 are Range objects that specify the start and end cells, to return a Range object. The following example sets the border line style for cells A1:J10.

Be aware that the period in front of each occurrence of the Cells property is required if the result of the preceding With statement is to be applied to the Cells property. In this case, it indicates that the cells are on worksheet one (without the period, the Cells property would return cells on the active sheet).

Use Rows on a worksheet to obtain a range consisting all rows on the worksheet. You can access single rows via Item(row), where row is the row index. Item can be omitted since the call is forwarded to it by the default member of Range.

It’s not legal to provide the second parameter of Item for ranges consisting of rows. You first have to convert it to single cells via Cells.

The following example deletes row 5 and 10 of the first sheet of the active workbook.

Use Columns on a worksheet to obtain a range consisting all columns on the worksheet. You can access single columns via Item(row) [sic], where row is the column index given as a number or as an A1-style column address. Item can be omitted since the call is forwarded to it by the default member of Range.

It’s not legal to provide the second parameter of Item for ranges consisting of columns. You first have to convert it to single cells via Cells.

The following example deletes column «B», «C», «E», and «J» of the first sheet of the active workbook.

Use_expression_.Rows, where expression is an expression that returns a Range object, to obtain a range consisting of the rows in the first area of the range. You can access single rows via Item(row), where row is the relative row index from the top of the first area of the range. Item can be omitted since the call is forwarded to it by the default member of Range.

It’s not legal to provide the second parameter of Item for ranges consisting of rows. You first have to convert it to single cells via Cells.

The following example deletes the ranges C8:D8 and C6:D6 of the first sheet of the active workbook.

Use_expression_.Columns, where expression is an expression that returns a Range object, to obtain a range consisting of the columns in the first area of the range. You can access single columns via Item(row) [sic], where row is the relative column index from the left of the first area of the range given as a number or as an A1-style column address. Item can be omitted since the call is forwarded to it by the default member of Range.

It’s not legal to provide the second parameter of Item for ranges consisting of columns. You first have to convert it to single cells via Cells.

The following example deletes the ranges L2:L10, G2:G10, F2:F10 and D2:D10 of the first sheet of the active workbook.

Use Offset (row, column), where row and column are the row and column offsets, to return a range at a specified offset to another range. The following example selects the cell three rows down from and one column to the right of the cell in the upper-left corner of the current selection. You cannot select a cell that is not on the active sheet, so you must first activate the worksheet.

Use Union (range1, range2, . ) to return multiple-area ranges—that is, ranges composed of two or more contiguous blocks of cells. The following example creates an object defined as the union of ranges A1:B2 and C3:D4, and then selects the defined range.

If you work with selections that contain more than one area, the Areas property is useful. It divides a multiple-area selection into individual Range objects and then returns the objects as a collection. Use the Count property on the returned collection to verify a selection that contains more than one area, as shown in the following example.

This example uses the AdvancedFilter method of the Range object to create a list of the unique values, and the number of times those unique values occur, in the range of column A.

Methods

Properties

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Range object (Excel)

vbaxl10.chm143072

vbaxl10.chm143072

excel

Excel.Range

b8207778-0dcc-4570-1234-f130532cc8cd

08/14/2019

high

Range object (Excel)

Represents a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3D range.

[!includeAdd-ins note]

Remarks

The default member of Range forwards calls without parameters to the Value property and calls with parameters to the Item member. Accordingly, someRange = someOtherRange is equivalent to someRange.Value = someOtherRange.Value, someRange(1) to someRange.Item(1) and someRange(1,1) to someRange.Item(1,1).

The following properties and methods for returning a Range object are described in the Example section:

  • Range and Cells properties of the Worksheet object
  • Range and Cells properties of the Range object
  • Rows and Columns properties of the Worksheet object
  • Rows and Columns properties of the Range object
  • Offset property of the Range object
  • Union method of the Application object

Example

Use Range (arg), where arg names the range, to return a Range object that represents a single cell or a range of cells. The following example places the value of cell A1 in cell A5.

Worksheets("Sheet1").Range("A5").Value = _ 
    Worksheets("Sheet1").Range("A1").Value

The following example fills the range A1:H8 with random numbers by setting the formula for each cell in the range. When it’s used without an object qualifier (an object to the left of the period), the Range property returns a range on the active sheet. If the active sheet isn’t a worksheet, the method fails.

Use the Activate method of the Worksheet object to activate a worksheet before you use the Range property without an explicit object qualifier.

Worksheets("Sheet1").Activate 
Range("A1:H8").Formula = "=Rand()"    'Range is on the active sheet

The following example clears the contents of the range named Criteria.

[!NOTE]
If you use a text argument for the range address, you must specify the address in A1-style notation (you cannot use R1C1-style notation).

Worksheets(1).Range("Criteria").ClearContents

Use Cells on a worksheet to obtain a range consisting all single cells on the worksheet. You can access single cells via Item(row, column), where row is the row index and column is the column index.
Item can be omitted since the call is forwarded to it by the default member of Range.
The following example sets the value of cell A1 to 24 and of cell B1 to 42 on the first sheet of the active workbook.

Worksheets(1).Cells(1, 1).Value = 24
Worksheets(1).Cells.Item(1, 2).Value = 42

The following example sets the formula for cell A2.

ActiveSheet.Cells(2, 1).Formula = "=Sum(B1:B5)"

Although you can also use Range("A1") to return cell A1, there may be times when the Cells property is more convenient because you can use a variable for the row or column. The following example creates column and row headings on Sheet1. Be aware that after the worksheet has been activated, the Cells property can be used without an explicit sheet declaration (it returns a cell on the active sheet).

[!NOTE]
Although you could use Visual Basic string functions to alter A1-style references, it is easier (and better programming practice) to use the Cells(1, 1) notation.

Sub SetUpTable() 
Worksheets("Sheet1").Activate 
For TheYear = 1 To 5 
    Cells(1, TheYear + 1).Value = 1990 + TheYear 
Next TheYear 
For TheQuarter = 1 To 4 
    Cells(TheQuarter + 1, 1).Value = "Q" & TheQuarter 
Next TheQuarter 
End Sub

Use_expression_.Cells, where expression is an expression that returns a Range object, to obtain a range with the same address consisting of single cells.
On such a range, you access single cells via Item(row, column), where are relative to the upper-left corner of the first area of the range.
Item can be omitted since the call is forwarded to it by the default member of Range.
The following example sets the formula for cell C5 and D5 of the first sheet of the active workbook.

Worksheets(1).Range("C5:C10").Cells(1, 1).Formula = "=Rand()"
Worksheets(1).Range("C5:C10").Cells.Item(1, 2).Formula = "=Rand()"

Use Range (cell1, cell2), where cell1 and cell2 are Range objects that specify the start and end cells, to return a Range object. The following example sets the border line style for cells A1:J10.

[!NOTE]
Be aware that the period in front of each occurrence of the Cells property is required if the result of the preceding With statement is to be applied to the Cells property. In this case, it indicates that the cells are on worksheet one (without the period, the Cells property would return cells on the active sheet).

With Worksheets(1) 
    .Range(.Cells(1, 1), _ 
        .Cells(10, 10)).Borders.LineStyle = xlThick 
End With

Use Rows on a worksheet to obtain a range consisting all rows on the worksheet. You can access single rows via Item(row), where row is the row index.
Item can be omitted since the call is forwarded to it by the default member of Range.

[!NOTE]
It’s not legal to provide the second parameter of Item for ranges consisting of rows. You first have to convert it to single cells via Cells.

The following example deletes row 5 and 10 of the first sheet of the active workbook.

Worksheets(1).Rows(10).Delete
Worksheets(1).Rows.Item(5).Delete

Use Columns on a worksheet to obtain a range consisting all columns on the worksheet. You can access single columns via Item(row) [sic], where row is the column index given as a number or as an A1-style column address.
Item can be omitted since the call is forwarded to it by the default member of Range.

[!NOTE]
It’s not legal to provide the second parameter of Item for ranges consisting of columns. You first have to convert it to single cells via Cells.

The following example deletes column «B», «C», «E», and «J» of the first sheet of the active workbook.

Worksheets(1).Columns(10).Delete
Worksheets(1).Columns.Item(5).Delete
Worksheets(1).Columns("C").Delete
Worksheets(1).Columns.Item("B").Delete

Use_expression_.Rows, where expression is an expression that returns a Range object, to obtain a range consisting of the rows in the first area of the range.
You can access single rows via Item(row), where row is the relative row index from the top of the first area of the range.
Item can be omitted since the call is forwarded to it by the default member of Range.

[!NOTE]
It’s not legal to provide the second parameter of Item for ranges consisting of rows. You first have to convert it to single cells via Cells.

The following example deletes the ranges C8:D8 and C6:D6 of the first sheet of the active workbook.

Worksheets(1).Range("C5:D10").Rows(4).Delete
Worksheets(1).Range("C5:D10").Rows.Item(2).Delete

Use_expression_.Columns, where expression is an expression that returns a Range object, to obtain a range consisting of the columns in the first area of the range.
You can access single columns via Item(row) [sic], where row is the relative column index from the left of the first area of the range given as a number or as an A1-style column address.
Item can be omitted since the call is forwarded to it by the default member of Range.

[!NOTE]
It’s not legal to provide the second parameter of Item for ranges consisting of columns. You first have to convert it to single cells via Cells.

The following example deletes the ranges L2:L10, G2:G10, F2:F10 and D2:D10 of the first sheet of the active workbook.

Worksheets(1).Range("C5:Z10").Columns(10).Delete
Worksheets(1).Range("C5:Z10").Columns.Item(5).Delete
Worksheets(1).Range("C5:Z10").Columns("D").Delete
Worksheets(1).Range("C5:Z10").Columns.Item("B").Delete

Use Offset (row, column), where row and column are the row and column offsets, to return a range at a specified offset to another range. The following example selects the cell three rows down from and one column to the right of the cell in the upper-left corner of the current selection. You cannot select a cell that is not on the active sheet, so you must first activate the worksheet.

Worksheets("Sheet1").Activate 
  'Can't select unless the sheet is active 
Selection.Offset(3, 1).Range("A1").Select

Use Union (range1, range2, …) to return multiple-area ranges—that is, ranges composed of two or more contiguous blocks of cells. The following example creates an object defined as the union of ranges A1:B2 and C3:D4, and then selects the defined range.

Dim r1 As Range, r2 As Range, myMultiAreaRange As Range 
Worksheets("sheet1").Activate 
Set r1 = Range("A1:B2") 
Set r2 = Range("C3:D4") 
Set myMultiAreaRange = Union(r1, r2) 
myMultiAreaRange.Select

If you work with selections that contain more than one area, the Areas property is useful. It divides a multiple-area selection into individual Range objects and then returns the objects as a collection. Use the Count property on the returned collection to verify a selection that contains more than one area, as shown in the following example.

Sub NoMultiAreaSelection() 
    NumberOfSelectedAreas = Selection.Areas.Count 
    If NumberOfSelectedAreas > 1 Then 
        MsgBox "You cannot carry out this command " & _ 
            "on multi-area selections" 
    End If 
End Sub

This example uses the AdvancedFilter method of the Range object to create a list of the unique values, and the number of times those unique values occur, in the range of column A.

Sub Create_Unique_List_Count()
    'Excel workbook, the source and target worksheets, and the source and target ranges.
    Dim wbBook As Workbook
    Dim wsSource As Worksheet
    Dim wsTarget As Worksheet
    Dim rnSource As Range
    Dim rnTarget As Range
    Dim rnUnique As Range
    'Variant to hold the unique data
    Dim vaUnique As Variant
    'Number of unique values in the data
    Dim lnCount As Long
    
    'Initialize the Excel objects
    Set wbBook = ThisWorkbook
    With wbBook
        Set wsSource = .Worksheets("Sheet1")
        Set wsTarget = .Worksheets("Sheet2")
    End With
    
    'On the source worksheet, set the range to the data stored in column A
    With wsSource
        Set rnSource = .Range(.Range("A1"), .Range("A100").End(xlDown))
    End With
    
    'On the target worksheet, set the range as column A.
    Set rnTarget = wsTarget.Range("A1")
    
    'Use AdvancedFilter to copy the data from the source to the target,
    'while filtering for duplicate values.
    rnSource.AdvancedFilter Action:=xlFilterCopy, _
                            CopyToRange:=rnTarget, _
                            Unique:=True
                            
    'On the target worksheet, set the unique range on Column A, excluding the first cell
    '(which will contain the "List" header for the column).
    With wsTarget
        Set rnUnique = .Range(.Range("A2"), .Range("A100").End(xlUp))
    End With
    
    'Assign all the values of the Unique range into the Unique variant.
    vaUnique = rnUnique.Value
    
    'Count the number of occurrences of every unique value in the source data,
    'and list it next to its relevant value.
    For lnCount = 1 To UBound(vaUnique)
        rnUnique(lnCount, 1).Offset(0, 1).Value = _
            Application.Evaluate("COUNTIF(" & _
            rnSource.Address(External:=True) & _
            ",""" & rnUnique(lnCount, 1).Text & """)")
    Next lnCount
    
    'Label the column of occurrences with "Occurrences"
    With rnTarget.Offset(0, 1)
        .Value = "Occurrences"
        .Font.Bold = True
    End With

End Sub

Methods

  • Activate
  • AddComment
  • AddCommentThreaded
  • AdvancedFilter
  • AllocateChanges
  • ApplyNames
  • ApplyOutlineStyles
  • AutoComplete
  • AutoFill
  • AutoFilter
  • AutoFit
  • AutoOutline
  • BorderAround
  • Calculate
  • CalculateRowMajorOrder
  • CheckSpelling
  • Clear
  • ClearComments
  • ClearContents
  • ClearFormats
  • ClearHyperlinks
  • ClearNotes
  • ClearOutline
  • ColumnDifferences
  • Consolidate
  • ConvertToLinkedDataType
  • Copy
  • CopyFromRecordset
  • CopyPicture
  • CreateNames
  • Cut
  • DataTypeToText
  • DataSeries
  • Delete
  • DialogBox
  • Dirty
  • DiscardChanges
  • EditionOptions
  • ExportAsFixedFormat
  • FillDown
  • FillLeft
  • FillRight
  • FillUp
  • Find
  • FindNext
  • FindPrevious
  • FlashFill
  • FunctionWizard
  • Group
  • Insert
  • InsertIndent
  • Justify
  • ListNames
  • Merge
  • NavigateArrow
  • NoteText
  • Parse
  • PasteSpecial
  • PrintOut
  • PrintPreview
  • RemoveDuplicates
  • RemoveSubtotal
  • Replace
  • RowDifferences
  • Run
  • Select
  • SetCellDataTypeFromCell
  • SetPhonetic
  • Show
  • ShowCard
  • ShowDependents
  • ShowErrors
  • ShowPrecedents
  • Sort
  • SortSpecial
  • Speak
  • SpecialCells
  • SubscribeTo
  • Subtotal
  • Table
  • TextToColumns
  • Ungroup
  • UnMerge

Properties

  • AddIndent
  • Address
  • AddressLocal
  • AllowEdit
  • Application
  • Areas
  • Borders
  • Cells
  • Characters
  • Column
  • Columns
  • ColumnWidth
  • Comment
  • CommentThreaded
  • Count
  • CountLarge
  • Creator
  • CurrentArray
  • CurrentRegion
  • Dependents
  • DirectDependents
  • DirectPrecedents
  • DisplayFormat
  • End
  • EntireColumn
  • EntireRow
  • Errors
  • Font
  • FormatConditions
  • Formula
  • FormulaArray
  • FormulaHidden
  • FormulaLocal
  • FormulaR1C1
  • FormulaR1C1Local
  • HasArray
  • HasFormula
  • HasRichDataType
  • Height
  • Hidden
  • HorizontalAlignment
  • Hyperlinks
  • ID
  • IndentLevel
  • Interior
  • Item
  • Left
  • LinkedDataTypeState
  • ListHeaderRows
  • ListObject
  • LocationInTable
  • Locked
  • MDX
  • MergeArea
  • MergeCells
  • Name
  • Next
  • NumberFormat
  • NumberFormatLocal
  • Offset
  • Orientation
  • OutlineLevel
  • PageBreak
  • Parent
  • Phonetic
  • Phonetics
  • PivotCell
  • PivotField
  • PivotItem
  • PivotTable
  • Precedents
  • PrefixCharacter
  • Previous
  • QueryTable
  • Range
  • ReadingOrder
  • Resize
  • Row
  • RowHeight
  • Rows
  • ServerActions
  • ShowDetail
  • ShrinkToFit
  • SoundNote
  • SparklineGroups
  • Style
  • Summary
  • Text
  • Top
  • UseStandardHeight
  • UseStandardWidth
  • Validation
  • Value
  • Value2
  • VerticalAlignment
  • Width
  • Worksheet
  • WrapText
  • XPath

See also

  • Excel Object Model Reference

[!includeSupport and feedback]

  • Remove From My Forums
  • Question

  • Hi,

    I would like to ask a question on range.

    Is there a VBA function to get the first and last row and column of a range?

    Bob

Answers

  • Without SpecialCells:

    Dim r As Range
    Set r = ActiveSheet.UsedRange
    nLastRow = r.Rows.Count + r.Row — 1
    MsgBox («last row » & nLastRow)
    nLastColumn = r.Columns.Count + r.Column — 1
    MsgBox («last column » & nLastColumn)
    nFirstRow = r.Row
    MsgBox («first row » & nFirstRow)
    nFirstColumn = r.Column
    MsgBox («first column » & nFirstColumn)


    gsnu201106

    • Marked as answer by

      Wednesday, September 7, 2011 8:28 PM

  • The first row of a range is:   rangeObject.Row
    The first column of a range is:   rangeObject.Column

    The SpecialCells method can return the bottom right corner cell (most of the time)…
    Dim BRC As Range
    Set BRC =  rangeObject.Cells.SpecialCells(xlCellTypeLastCell)
    MsgBox BRC.Row & vbCr & BRC.Column
    ‘—
    Jim Cone
    Portland, Oregon USA
    http://blog.contextures.com/archives/2011/07/18/find-last-row-with-excel-vba/
    (workbook with «universal» Last Row function code — free)

    • Edited by
      Jim Cone
      Tuesday, September 6, 2011 7:29 PM
    • Marked as answer by
      Bob Sun
      Wednesday, September 7, 2011 8:28 PM


VBA Select

It is very common to find the .Select methods in saved macro recorder code, next to a Range object.

.Select is used to select one or more elements of Excel (as can be done by using the mouse) allowing further manipulation of them.

Selecting cells with the mouse:

Select with the Mouse

Selecting cells with VBA:

    'Range([cell1],[cell2])
    Range(Cells(1, 1), Cells(9, 5)).Select
    Range("A1", "E9").Select
    Range("A1:E9").Select

Each of the above lines select the range from «A1» to «E9».

Select with VBA


VBA Select CurrentRegion

If a region is populated by data with no empty cells, an option for an automatic selection is the CurrentRegion property alongside the .Select method.

CurrentRegion.Select will select, starting from a Range, all the area populated with data.

    Range("A1").CurrentRegion.Select

CurrentRegion

Make sure there are no gaps between values, as CurrentRegion will map the region through adjoining cells (horizontal, vertical and diagonal).

  Range("A1").CurrentRegion.Select

With all the adjacent data

CurrentRegion Data

Not all adjacent data

CurrentRegion Missing Data

«C4» is not selected because it is not immediately adjacent to any filled cells.


VBA ActiveCell

The ActiveCell property brings up the active cell of the worksheet.

In the case of a selection, it is the only cell that stays white.

A worksheet has only one active cell.

    Range("B2:C4").Select
    ActiveCell.Value = "Active"

ActiveCell

Usually the ActiveCell property is assigned to the first cell (top left) of a Range, although it can be different when the selection is made manually by the user (without macros).

ActiveCell Under

The AtiveCell property can be used with other commands, such as Resize.


VBA Selection

After selecting the desired cells, we can use Selection to refer to it and thus make changes:

    Range("A1:D7").Select
    Selection = 7

Example Selection

Selection also accepts methods and properties (which vary according to what was selected).

    Selection.ClearContents 'Deletes only the contents of the selection
    Selection.Interior.Color = RGB(255, 255, 0) 'Adds background color to the selection

Clear Selection

As in this case a cell range has been selected, the Selection will behave similarly to a Range. Therefore, Selection should also accept the .Interior.Color property.

RGB (Red Green Blue) is a color system used in a number of applications and languages. The input values for each color, in the example case, ranges from 0 to 255.


Selection FillDown

If there is a need to replicate a formula to an entire selection, you can use the .FillDown method

    Selection.FillDown

Before the FillDown

Before Filldown

After the FillDown

After FillDown

.FillDown is a method applicable to Range. Since the Selection was done in a range of cells (equivalent to a Range), the method will be accepted.

.FillDown replicates the Range/Selection formula of the first line, regardless of which ActiveCell is selected.

.FillDown can be used at intervals greater than one column (E.g. Range(«B1:C2»).FillDown will replicate the formulas of B1 and C1 to B2 and C2 respectively).


VBA EntireRow and EntireColumn

You can select one or multiple rows or columns with VBA.

    Range("B2").EntireRow.Select
    Range("C3:D3").EntireColumn.Select

Select EntireColumn

The selection will always refer to the last command executed with Select.

To insert a row use the Insert method.

    Range("A7").EntireRow.Insert
    'In this case, the content of the seventh row will be shifted downward

To delete a row use the Delete method.

    Range("A7").EntireRow.Delete
    'In this case, the content of the eighth row will be moved to the seventh

VBA Rows and Columns

Just like with the EntireRow and EntireColumn property, you can use Rows and Columns to select a row or column.

    Columns(5).Select
    Rows(3).Select

Select Rows

To hide rows:

    Range("A1:C3").Rows.Hidden = True

Hidden Cells

In the above example, rows 1 to 3 of the worksheet were hidden.


VBA Row and Column

Row and Column are properties that are often used to obtain the numerical address of the first row or first column of a selection or a specific cell.

    Range("A3:H30").Row 'Referring to the row; returns 3
    Range("B3").Column  'Referring to the column; returns 2

The results of Row and Column are often used in loops or resizing.



Consolidating Your Learning

Suggested Exercise



SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2023 SuperExcelVBA | ABOUT

Protected by Copyscape

“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

Function Takes Returns Example Gives

Range

cell address multiple cells .Range(«A1:A4») $A$1:$A$4
Cells row, column one cell .Cells(1,5) $E$1
Offset row, column multiple cells Range(«A1:A2»)
.Offset(1,2)
$C$2:$C$3
Rows row(s) one or more rows .Rows(4)
.Rows(«2:4»)
$4:$4
$2:$4
Columns column(s) one or more columns .Columns(4)
.Columns(«B:D»)
$D:$D
$B:$D

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

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

' https://excelmacromastery.com/
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”).

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
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.

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
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:

' https://excelmacromastery.com/
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)

 
ImmediateWindow

 
ImmediateSampeText

 
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.

' https://excelmacromastery.com/
' 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

' https://excelmacromastery.com/
' 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

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
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:

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
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:
 

' https://excelmacromastery.com/
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:

' https://excelmacromastery.com/
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:

' https://excelmacromastery.com/
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.

' https://excelmacromastery.com/
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:

' https://excelmacromastery.com/
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.

' https://excelmacromastery.com/
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("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").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:

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
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
    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.

' https://excelmacromastery.com/
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

' https://excelmacromastery.com/
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.)

# Ways to refer to a single cell

The simplest way to refer to a single cell on the current Excel worksheet is simply to enclose the A1 form of its reference in square brackets:

Note that square brackets are just convenient syntactic sugar (opens new window) for the Evaluate method of the Application object, so technically, this is identical to the following code:

You could also call the Cells method which takes a row and a column and returns a cell reference.

Remember that whenever you pass a row and a column to Excel from VBA, the row is always first, followed by the column, which is confusing because it is the opposite of the common A1 notation where the column appears first.

In both of these examples, we did not specify a worksheet, so Excel will use the active sheet (the sheet that is in front in the user interface). You can specify the active sheet explicitly:

Or you can provide the name of a particular sheet:

There are a wide variety of methods that can be used to get from one range to another. For example, the Rows method can be used to get to the individual rows of any range, and the Cells method can be used to get to individual cells of a row or column, so the following code refers to cell C1:

# Creating a Range

A Range (opens new window) cannot be created or populated the same way a string would:

It is considered best practice to qualify your references (opens new window), so from now on we will use the same approach here.
More about Creating Object Variables (e.g. Range) on MSDN (opens new window) . More about Set Statement on MSDN (opens new window).

There are different ways to create the same Range:

Note in the example that Cells(2, 1) is equivalent to Range(«A2»). This is because Cells returns a Range object.
Some sources: Chip Pearson-Cells Within Ranges (opens new window); MSDN-Range Object (opens new window); John Walkenback-Referring To Ranges In Your VBA Code (opens new window).

Also note that in any instance where a number is used in the declaration of the range, and the number itself is outside of quotation marks, such as Range(«A» & 2), you can swap that number for a variable that contains an integer/long. For example:

If you are using double loops, Cells is better:

# Offset Property

  • Offset(Rows, Columns) — The operator used to statically reference another point from the current cell. Often used in loops. It should be understood that positive numbers in the rows section moves right, wheres as negatives move left. With the columns section positives move down and negatives move up.

i.e

This code selects B2, puts a new string there, then moves that string back to A1 afterwards clearing out B2.

# Saving a reference to a cell in a variable

To save a reference to a cell in a variable, you must use the Set syntax, for example:

later…

Why is the Set keyword required? Set tells Visual Basic that the value on the right hand side of the = is meant to be an object.

# How to Transpose Ranges (Horizontal to Vertical & vice versa)

Note: Copy/PasteSpecial also has a Paste Transpose option which updates the transposed cells’ formulas as well.

# Syntax

  • Set — The operator used to set a reference to an object, such as a Range
  • For Each — The operator used to loop through every item in a collection

Note that the variable names r, cell and others can be named however you like but should be named appropriately so the code is easier to understand for you and others.

Skip to content

Exceldome

Exceldome

This tutorial shows how to return the first row number from a selected range using an Excel formula or VBA

Example: Return first row number in a range

Return first row number in a range

METHOD 1. Return first row number in a range using Excel formula

EXCEL

This formula uses the Excel ROW function to return the row number of the first cell in the selected range. In this example the first row in the range is row 5.

METHOD 1. Return first row number in a range using VBA

VBA

Sub Return_first_row_number_in_range()

‘declare variables
Dim ws As Worksheet

Set ws = Worksheets(«Analysis»)

‘return the first column number in a range
ws.Range(«E5») = ws.Range(«B5:C10»).Row

End Sub

Explanation about how to return the first row number in a range

EXPLANATION

EXPLANATION

This tutorial shows how to return the first row number from a selected range through the use of an Excel formula or VBA.

Using the ROW function in both the Excel and VBA methods in will return the first row number in a selected range.

FORMULA
=ROW(range)

ARGUMENTS
range: A range of cells for which you want to return the first row number.

Related Topic Description Related Topic and Description
Return first column number in a range How to return the first column number from a selected range using Excel and VBA
Return row number of a specific value How to return a row number of a specific value using Excel and VBA
Related Functions Description Related Functions and Description
ROW Function The Excel ROW function returns the first row number of the selected reference

Понравилась статья? Поделить с друзьями:
  • Excel vba get all sheets
  • Excel vba listobject range
  • Excel vba function with no return value
  • Excel vba listobject listrows
  • Excel vba function private