Return to VBA Code Examples
This tutorial will show you how to use the Range.End property in VBA.
Most things that you do manually in an Excel workbook or worksheet can be automated in VBA code.
If you have a range of non-blank cells in Excel, and you press Ctrl+Down Arrow, your cursor will move to the last non-blank cell in the column you are in. Similarly, if you press Ctrl+Up Arrow, your cursor will move to the first non-blank cell. The same applies for a row using the Ctrl+Right Arrow or Ctrl+Left Arrow to go to the beginning or end of that row. All of these key combinations can be used within your VBA code using the End Function.
Range End Property Syntax
The Range.End Property allows you to move to a specific cell within the Current Region that you are working with.
expression.End (Direction)
the expression is the cell address (Range) of the cell where you wish to start from eg: Range(“A1”)
END is the property of the Range object being controlled.
Direction is the Excel constant that you are able to use. There are 4 choices available – xlDown, xlToLeft, xlToRight and xlUp.
Moving to the Last Cell
The procedure below will move you to the last cell in the Current Region of cells that you are in.
Sub GoToLast()
'move to the last cell occupied in the current region of cells
Range("A1").End(xlDown).Select
End Sub
Counting Rows
The following procedure allows you to use the xlDown constant with the Range End property to count how many rows are in your current region.
Sub GoToLastRowofRange()
Dim rw As Integer
Range("A1").Select
'get the last row in the current region
rw = Range("A1").End(xlDown).Row
'show how many rows are used
MsgBox "The last row used in this range is " & rw
End Sub
While the one below will count the columns in the range using the xlToRight constant.
Sub GoToLastCellofRange()
Dim col As Integer
Range("A1").Select
'get the last column in the current region
col = Range("A1").End(xlToRight).Column
'show how many columns are used
MsgBox "The last column used in this range is " & col
End Sub
Creating a Range Array
The procedure below allows us to start at the first cell in a range of cells, and then use the End(xlDown) property to find the last cell in the range of cells. We can then ReDim our array with the total rows in the Range, thereby allowing us to loop through the range of cells.
Sub PopulateArray()
'declare the array
Dim strSuppliers() As String
'declare the integer to count the rows
Dim n As Integer
'count the rows
n = Range("B1", Range("B1").End(xlDown)).Rows.Count
'initialise and populate the array
ReDim strCustomers(n)
'declare the integer for looping
Dim i As Integer
'populate the array
For i = 0 To n
strCustomers(i) = Range("B1").Offset(i, 0).Value
Next i
'show message box with values of array
MsgBox Join(strCustomers, vbCrLf)
End Sub
When we run this procedure, it will return the following message box.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
Свойство End объекта Range применяется для поиска первых и последних заполненных ячеек в VBA Excel — аналог сочетания клавиш Ctrl+стрелка.
Свойство End
объекта Range
возвращает объект Range
, представляющий ячейку в конце или начале заполненной значениями области исходного диапазона по строке или столбцу в зависимости от указанного направления. Является в VBA Excel программным аналогом сочетания клавиш — Ctrl+стрелка (вверх, вниз, вправо, влево).
Возвращаемая свойством Range.End
ячейка в зависимости от расположения и содержания исходной:
Исходная ячейка | Возвращаемая ячейка |
---|---|
Исходная ячейка пустая | Первая заполненная ячейка или, если в указанном направлении заполненных ячеек нет, последняя ячейка строки или столбца в заданном направлении. |
Исходная ячейка не пустая и не крайняя внутри исходного заполненного диапазона в указанном направлении | Последняя заполненная ячейка исходного заполненного диапазона в указанном направлении |
Исходная ячейка не пустая, но в указанном направлении является крайней внутри исходного заполненного диапазона | Первая заполненная ячейка следующего заполненного диапазона или, если в указанном направлении заполненных ячеек нет, последняя ячейка строки или столбца в заданном направлении. |
Синтаксис
Expression.End (Direction) |
Expression
— выражение (переменная), представляющее объект Range
.
Параметры
Параметр | Описание |
---|---|
Direction | Константа из коллекции XlDirection , задающая направление перемещения. Обязательный параметр. |
Константы XlDirection
:
Константа | Значение | Направление |
---|---|---|
xlDown | -4121 | Вниз |
xlToLeft | -4159 | Влево |
xlToRight | -4161 | Вправо |
xlUp | -4162 | Вверх |
Примеры
Скриншот области рабочего листа для визуализации примеров применения свойства Range.End
:
Примеры возвращаемых ячеек свойством End
объекта Range("C10")
с разными значениями параметра Direction:
Выражение с Range.End | Возвращенная ячейка |
---|---|
Set myRange = Range("C10").End(xlDown) |
Range("C16") |
Set myRange = Range("C10").End(xlToLeft) |
Range("A10") |
Set myRange = Range("C10").End(xlToRight) |
Range("E10") |
Set myRange = Range("C10").End(xlUp) |
Range("C4") |
Пример возвращения заполненной значениями части столбца:
Sub Primer() Dim myRange As Range Set myRange = Range(Range(«C10»), Range(«C10»).End(xlDown)) MsgBox myRange.Address ‘Результат: $C$10:$C$16 End Sub |
Содержание
- VBA Range.End (xlDown, xlUp, xlToRight, xlToLeft)
- Range End Property Syntax
- Moving to the Last Cell
- Counting Rows
- Creating a Range Array
- VBA Coding Made Easy
- VBA Code Examples Add-in
- Выбор ячеек и диапазонов с помощью процедур Visual Basic в Excel
- Выбор ячейки на активном листе
- Выбор ячейки на другом листе в той же книге
- Выбор ячейки на листе в другой книге
- Выбор диапазона ячеек на активном листе
- Выбор диапазона ячеек на другом листе в той же книге
- Выбор диапазона ячеек на листе в другой книге
- Выбор именованного диапазона на активном листе
- Выбор именованного диапазона на другом листе в той же книге
- Выбор именованного диапазона на листе в другой книге
- Выбор ячейки относительно активной ячейки
- Выбор ячейки относительно другой (не активной) ячейки
- Выбор смещения диапазона ячеек из указанного диапазона
- Выбор указанного диапазона и изменение его размера
- Выбор указанного диапазона, его смещение и изменение размера
- Выбор объединения двух или более указанных диапазонов
- Выбор пересечения двух или более указанных диапазонов
- Выбор последней ячейки столбца непрерывных данных
- Выбор пустой ячейки в нижней части столбца непрерывных данных
- Выбор целого диапазона смежных ячеек в столбце
- Как выбрать весь диапазон несмежных ячеек в столбце
- Выбор прямоугольного диапазона ячеек
- Выбор нескольких несмежных столбцов разной длины
- Примечания к примерам
- How to select cells/ranges by using Visual Basic procedures in Excel
- How to Select a Cell on the Active Worksheet
- How to Select a Cell on Another Worksheet in the Same Workbook
- How to Select a Cell on a Worksheet in a Different Workbook
- How to Select a Range of Cells on the Active Worksheet
- How to Select a Range of Cells on Another Worksheet in the Same Workbook
- How to Select a Range of Cells on a Worksheet in a Different Workbook
- How to Select a Named Range on the Active Worksheet
- How to Select a Named Range on Another Worksheet in the Same Workbook
- How to Select a Named Range on a Worksheet in a Different Workbook
- How to Select a Cell Relative to the Active Cell
- How to Select a Cell Relative to Another (Not the Active) Cell
- How to Select a Range of Cells Offset from a Specified Range
- How to Select a Specified Range and Resize the Selection
- How to Select a Specified Range, Offset It, and Then Resize It
- How to Select the Union of Two or More Specified Ranges
- How to Select the Intersection of Two or More Specified Ranges
- How to Select the Last Cell of a Column of Contiguous Data
- How to Select the Blank Cell at Bottom of a Column of Contiguous Data
- How to Select an Entire Range of Contiguous Cells in a Column
- How to Select an Entire Range of Non-Contiguous Cells in a Column
- How to Select a Rectangular Range of Cells
- How to Select Multiple Non-Contiguous Columns of Varying Length
- Notes on the examples
VBA Range.End (xlDown, xlUp, xlToRight, xlToLeft)
In this Article
This tutorial will show you how to use the Range.End property in VBA.
Most things that you do manually in an Excel workbook or worksheet can be automated in VBA code.
If you have a range of non-blank cells in Excel, and you press Ctrl+Down Arrow, your cursor will move to the last non-blank cell in the column you are in. Similarly, if you press Ctrl+Up Arrow, your cursor will move to the first non-blank cell. The same applies for a row using the Ctrl+Right Arrow or Ctrl+Left Arrow to go to the beginning or end of that row. All of these key combinations can be used within your VBA code using the End Function.
Range End Property Syntax
The Range.End Property allows you to move to a specific cell within the Current Region that you are working with.
expression.End (Direction)
the expression is the cell address (Range) of the cell where you wish to start from eg: Range(“A1”)
END is the property of the Range object being controlled.
Direction is the Excel constant that you are able to use. There are 4 choices available – xlDown, xlToLeft, xlToRight and xlUp.
Moving to the Last Cell
The procedure below will move you to the last cell in the Current Region of cells that you are in.
Counting Rows
The following procedure allows you to use the xlDown constant with the Range End property to count how many rows are in your current region.
While the one below will count the columns in the range using the xlToRight constant.
Creating a Range Array
The procedure below allows us to start at the first cell in a range of cells, and then use the End(xlDown) property to find the last cell in the range of cells. We can then ReDim our array with the total rows in the Range, thereby allowing us to loop through the range of cells.
When we run this procedure, it will return the following message box.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Выбор ячеек и диапазонов с помощью процедур Visual Basic в Excel
Корпорация Майкрософт предоставляет примеры программирования только в целях демонстрации без явной или подразумеваемой гарантии. Данное положение включает, но не ограничивается этим, подразумеваемые гарантии товарной пригодности или соответствия отдельной задаче. Эта статья предполагает, что пользователь знаком с представленным языком программирования и средствами, используемыми для создания и отладки процедур. Специалисты технической поддержки Майкрософт могут пояснить работу той или иной процедуры, но модификация примеров и их адаптация к задачам разработчика не предусмотрена. В примерах в этой статье используются методы Visual Basic, перечисленные в следующей таблице.
В примерах в этой статье используются свойства, приведенные в следующей таблице.
Выбор ячейки на активном листе
Чтобы выбрать ячейку D5 на активном листе, можно использовать один из следующих примеров:
Выбор ячейки на другом листе в той же книге
Чтобы выбрать ячейку E6 на другом листе в той же книге, можно использовать один из следующих примеров:
Кроме того, можно активировать лист, а затем выбрать ячейку с помощью метода 1, приведенного выше:
Выбор ячейки на листе в другой книге
Чтобы выбрать ячейку F7 на листе в другой книге, можно использовать один из следующих примеров:
Кроме того, можно активировать лист, а затем выбрать ячейку с помощью метода 1, приведенного выше:
Выбор диапазона ячеек на активном листе
Чтобы выбрать диапазон C2:D10 на активном листе, можно использовать любой из следующих примеров:
Выбор диапазона ячеек на другом листе в той же книге
Чтобы выбрать диапазон D3:E11 на другом листе в той же книге, можно использовать один из следующих примеров:
Кроме того, можно активировать лист, а затем выбрать диапазон с помощью метода 4, приведенного выше:
Выбор диапазона ячеек на листе в другой книге
Чтобы выбрать диапазон E4:F12 на листе в другой книге, можно использовать один из следующих примеров:
Кроме того, можно активировать лист, а затем выбрать диапазон с помощью метода 4, приведенного выше:
Выбор именованного диапазона на активном листе
Чтобы выбрать именованный диапазон «Тест» на активном листе, можно использовать один из следующих примеров:
Выбор именованного диапазона на другом листе в той же книге
Чтобы выбрать именованный диапазон «Тест» на другом листе в той же книге, можно использовать следующий пример:
Или можно активировать лист, а затем использовать метод 7 выше, чтобы выбрать именованный диапазон:
Выбор именованного диапазона на листе в другой книге
Чтобы выбрать именованный диапазон «Тест» на листе в другой книге, можно использовать следующий пример:
Или можно активировать лист, а затем использовать метод 7 выше, чтобы выбрать именованный диапазон:
Выбор ячейки относительно активной ячейки
Чтобы выбрать ячейку с пятью строками ниже и четырьмя столбцами слева от активной ячейки, можно использовать следующий пример:
Чтобы выбрать ячейку с двумя строками выше и тремя столбцами справа от активной ячейки, можно использовать следующий пример:
При попытке выбрать ячейку, которая находится вне листа, произойдет ошибка. Первый пример, показанный выше, вернет ошибку, если активная ячейка находится в столбцах A–D, так как перемещение четырех столбцов влево приведет к переходу активной ячейки на недопустимый адрес ячейки.
Выбор ячейки относительно другой (не активной) ячейки
Чтобы выбрать ячейку с пятью строками ниже и четырьмя столбцами справа от ячейки C7, можно использовать один из следующих примеров:
Выбор смещения диапазона ячеек из указанного диапазона
Чтобы выбрать диапазон ячеек того же размера, что и именованный диапазон «Тест», но сдвинув четыре строки вниз и три столбца вправо, можно использовать следующий пример:
Если именованный диапазон находится на другом (не активном) листе, сначала активируйте этот лист, а затем выберите диапазон, используя следующий пример:
Выбор указанного диапазона и изменение его размера
Чтобы выбрать именованный диапазон «База данных», а затем расширить выделение на пять строк, можно использовать следующий пример:
Выбор указанного диапазона, его смещение и изменение размера
Чтобы выбрать диапазон из четырех строк ниже и трех столбцов справа от именованного диапазона «База данных» и включить две строки и один столбец больше именованного диапазона, можно использовать следующий пример:
Выбор объединения двух или более указанных диапазонов
Чтобы выбрать объединение (то есть объединенную область) двух именованных диапазонов «Тест» и «Образец», можно использовать следующий пример:
Значение , чтобы оба диапазона были на одном листе для работы в этом примере. Обратите внимание, что метод Union не работает на разных листах. Например, эта строка работает нормально.
возвращает сообщение об ошибке:
Сбой метода Union класса приложения
Выбор пересечения двух или более указанных диапазонов
Чтобы выбрать пересечение двух именованных диапазонов «Тест» и «Образец», можно использовать следующий пример:
Обратите внимание, что для работы в этом примере оба диапазона должны находиться на одном листе.
Примеры 17–21 в этой статье относятся к следующему примеру набора данных. В каждом примере указывается диапазон ячеек в выборке данных, которые будут выбраны.
Выбор последней ячейки столбца непрерывных данных
Чтобы выбрать последнюю ячейку в непрерывном столбце, используйте следующий пример:
При использовании этого кода с образцом таблицы будет выбрана ячейка A4.
Выбор пустой ячейки в нижней части столбца непрерывных данных
Чтобы выбрать ячейку под диапазоном смежных ячеек, используйте следующий пример:
При использовании этого кода с образцом таблицы будет выбрана ячейка A5.
Выбор целого диапазона смежных ячеек в столбце
Чтобы выбрать диапазон смежных ячеек в столбце, используйте один из следующих примеров:
При использовании этого кода с образцом таблицы будут выделены ячейки A1–A4.
Как выбрать весь диапазон несмежных ячеек в столбце
Чтобы выбрать диапазон несмежных ячеек, используйте один из следующих примеров:
При использовании этого кода с образцом таблицы будут выделены ячейки A1–A6.
Выбор прямоугольного диапазона ячеек
Чтобы выбрать прямоугольный диапазон ячеек вокруг ячейки, используйте метод CurrentRegion. Диапазон, выбранный методом CurrentRegion, — это область, ограниченная любым сочетанием пустых строк и пустых столбцов. Ниже приведен пример использования метода CurrentRegion.
Этот код будет выбирать ячейки A1–C4. Ниже перечислены другие примеры выбора того же диапазона ячеек.
В некоторых случаях может потребоваться выбрать ячейки A1–C6. В этом примере метод CurrentRegion не будет работать из-за пустой строки в строке 5. В следующих примерах будут выделены все ячейки:
Выбор нескольких несмежных столбцов разной длины
Чтобы выбрать несколько несмежных столбцов разной длины, используйте следующий пример таблицы и макроса:
При использовании этого кода с образцом таблицы будут выбраны ячейки A1:A3 и C1:C6.
Примечания к примерам
Свойство ActiveSheet обычно можно опустить, так как оно подразумевается, если конкретный лист не называется. Например, вместо
вы можете использовать:
Свойство ActiveWorkbook также обычно можно опустить. Если не указано имя конкретной книги, она подразумевается.
При использовании метода Application.Goto, если вы хотите использовать два метода Cells в методе Range, если указанный диапазон находится на другом (не активном) листе, необходимо каждый раз включать объект Sheets. Например:
Для любого элемента в кавычках (например, именованного диапазона Test) можно также использовать переменную, значение которой является текстовой строкой. Например, вместо
Источник
How to select cells/ranges by using Visual Basic procedures in Excel
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. The examples in this article use the Visual Basic methods listed in the following table.
The examples in this article use the properties in the following table.
How to Select a Cell on the Active Worksheet
To select cell D5 on the active worksheet, you can use either of the following examples:
How to Select a Cell on Another Worksheet in the Same Workbook
To select cell E6 on another worksheet in the same workbook, you can use either of the following examples:
Or, you can activate the worksheet, and then use method 1 above to select the cell:
How to Select a Cell on a Worksheet in a Different Workbook
To select cell F7 on a worksheet in a different workbook, you can use either of the following examples:
Or, you can activate the worksheet, and then use method 1 above to select the cell:
How to Select a Range of Cells on the Active Worksheet
To select the range C2:D10 on the active worksheet, you can use any of the following examples:
How to Select a Range of Cells on Another Worksheet in the Same Workbook
To select the range D3:E11 on another worksheet in the same workbook, you can use either of the following examples:
Or, you can activate the worksheet, and then use method 4 above to select the range:
How to Select a Range of Cells on a Worksheet in a Different Workbook
To select the range E4:F12 on a worksheet in a different workbook, you can use either of the following examples:
Or, you can activate the worksheet, and then use method 4 above to select the range:
How to Select a Named Range on the Active Worksheet
To select the named range «Test» on the active worksheet, you can use either of the following examples:
How to Select a Named Range on Another Worksheet in the Same Workbook
To select the named range «Test» on another worksheet in the same workbook, you can use the following example:
Or, you can activate the worksheet, and then use method 7 above to select the named range:
How to Select a Named Range on a Worksheet in a Different Workbook
To select the named range «Test» on a worksheet in a different workbook, you can use the following example:
Or, you can activate the worksheet, and then use method 7 above to select the named range:
How to Select a Cell Relative to the Active Cell
To select a cell that is five rows below and four columns to the left of the active cell, you can use the following example:
To select a cell that is two rows above and three columns to the right of the active cell, you can use the following example:
An error will occur if you try to select a cell that is «off the worksheet.» The first example shown above will return an error if the active cell is in columns A through D, since moving four columns to the left would take the active cell to an invalid cell address.
How to Select a Cell Relative to Another (Not the Active) Cell
To select a cell that is five rows below and four columns to the right of cell C7, you can use either of the following examples:
How to Select a Range of Cells Offset from a Specified Range
To select a range of cells that is the same size as the named range «Test» but that is shifted four rows down and three columns to the right, you can use the following example:
If the named range is on another (not the active) worksheet, activate that worksheet first, and then select the range using the following example:
How to Select a Specified Range and Resize the Selection
To select the named range «Database» and then extend the selection by five rows, you can use the following example:
How to Select a Specified Range, Offset It, and Then Resize It
To select a range four rows below and three columns to the right of the named range «Database» and include two rows and one column more than the named range, you can use the following example:
How to Select the Union of Two or More Specified Ranges
To select the union (that is, the combined area) of the two named ranges «Test» and «Sample,» you can use the following example:
that both ranges must be on the same worksheet for this example to work. Note also that the Union method does not work across sheets. For example, this line works fine.
returns the error message:
Union method of application class failed
How to Select the Intersection of Two or More Specified Ranges
To select the intersection of the two named ranges «Test» and «Sample,» you can use the following example:
Note that both ranges must be on the same worksheet for this example to work.
Examples 17-21 in this article refer to the following sample set of data. Each example states the range of cells in the sample data that would be selected.
How to Select the Last Cell of a Column of Contiguous Data
To select the last cell in a contiguous column, use the following example:
When this code is used with the sample table, cell A4 will be selected.
How to Select the Blank Cell at Bottom of a Column of Contiguous Data
To select the cell below a range of contiguous cells, use the following example:
When this code is used with the sample table, cell A5 will be selected.
How to Select an Entire Range of Contiguous Cells in a Column
To select a range of contiguous cells in a column, use one of the following examples:
When this code is used with the sample table, cells A1 through A4 will be selected.
How to Select an Entire Range of Non-Contiguous Cells in a Column
To select a range of cells that are non-contiguous, use one of the following examples:
When this code is used with the sample table, it will select cells A1 through A6.
How to Select a Rectangular Range of Cells
In order to select a rectangular range of cells around a cell, use the CurrentRegion method. The range selected by the CurrentRegion method is an area bounded by any combination of blank rows and blank columns. The following is an example of how to use the CurrentRegion method:
This code will select cells A1 through C4. Other examples to select the same range of cells are listed below:
In some instances, you may want to select cells A1 through C6. In this example, the CurrentRegion method will not work because of the blank line on Row 5. The following examples will select all of the cells:
How to Select Multiple Non-Contiguous Columns of Varying Length
To select multiple non-contiguous columns of varying length, use the following sample table and macro example:
When this code is used with the sample table, cells A1:A3 and C1:C6 will be selected.
Notes on the examples
The ActiveSheet property can usually be omitted, because it is implied if a specific sheet is not named. For example, instead of
The ActiveWorkbook property can also usually be omitted. Unless a specific workbook is named, the active workbook is implied.
When you use the Application.Goto method, if you want to use two Cells methods within the Range method when the specified range is on another (not the active) worksheet, you must include the Sheets object each time. For example:
For any item in quotation marks (for example, the named range «Test»), you can also use a variable whose value is a text string. For example, instead of
Источник
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
- VBA Insert Cell or Range in a worksheet – Syntax
- VBA Insert Range in a Worksheet – xlDown
- VBA Insert Range in a Worksheet – xlToRight
- VBA Insert Range in a Worksheet – EntireRow
- VBA Insert Range in a Worksheet – EntireColumn
- VBA Insert Range in a Worksheet – Instructions
Page load link
Go to Top
The following should work:
For k = 1 To lastCell
If Cells(k, 1).Value = rangeName Then
Range(Cells(k + 1, 1), Cells(k + 1, 1).End(xlDown)).Select
End If
Next k
Yet, I’d suggest that you code a bit more explicitly to ensure it works:
With Worksheets("SheetYouAreWorkingOn")
For k = 1 To lastCell
If .Cells(k, 1).Value = rangeName Then
.Range(.Cells(k + 1, 1), .Cells(k + 1, 1).End(xlDown)).Select
End If
Next k
End With
Tested with your sample data on an empty / new file:
Public Sub tmpSO()
Dim lastCell As Long
Dim rangeName As String
rangeName = "AGE"
With Worksheets("Sheet1")
lastCell = .Cells(.Rows.Count, 1).End(xlUp).Row
For k = 1 To lastCell
If .Cells(k, 1).Value = rangeName Then
.Range(.Cells(k + 1, 1), .Cells(k + 1, 1).End(xlDown)).Select
End If
Next k
End With
End Sub