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 |
In VBA, when we have to find the last row, there are many different methods. The most commonly used method is the End(XLDown) method. Other methods include finding the last value using the find function in VBA, End(XLDown). The row is the easiest way to get to the last row.
Excel VBA Last Row
If writing the code is your first progress in VBA, then making the code dynamic is your next step. Excel is full of cell referencesCell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1.read more. The moment we refer to the cell, it becomes fixed. If our data increases, we need to go back to the cell reference and change the references to make the result up to date.
For an example, look at the below code.
Code:
Sub Last_Row_Example1() Range("D2").Value = WorksheetFunction.Sum(Range("B2:B7")) End Sub
The above code says in D2 cell value should be the summation of Range (“B2:B7”).
Now, we will add more values to the list.
Now, if we run the code, it will not give us the updated result. Rather, it still sticks to the old range, i.e., Range (“B2: B7”).
That is where dynamic code is very important.
Finding the last used row in the column is crucial in making the code dynamic. This article will discuss finding the last row in Excel VBA.
Table of contents
- Excel VBA Last Row
- How to Find Last Used Row in the Column?
- Method #1
- Method #2
- Method #3
- Recommended Articles
- How to Find Last Used Row in the Column?
How to Find the Last Used Row in the Column?
Below are the examples to find the last used row in Excel VBA.
You can download this VBA Last Row Template here – VBA Last Row Template
Method #1
Before we explain the code, we want you to remember how you go to the last row in the normal worksheet.
We will use the shortcut key Ctrl + down arrow.
It will take us to the last used row before any empty cell. We will also use the same VBA method to find the last row.
Step 1: Define the variable as LONG.
Code:
Sub Last_Row_Example2() Dim LR As Long 'For understanding LR = Last Row End Sub
Step 2: We will assign this variable’s last used row number.
Code:
Sub Last_Row_Example2() Dim LR As Long 'For understanding LR = Last Row LR = End Sub
Step 3: Write the code as CELLS (Rows.Count,
Code:
Sub Last_Row_Example2() Dim LR As Long 'For understanding LR = Last Row LR = Cells(Rows.Count, End Sub
Step 4: Now, mention the column number as 1.
Code:
Sub Last_Row_Example2() Dim LR As Long 'For understanding LR = Last Row LR = Cells(Rows.Count, 1) End Sub
CELLS(Rows.Count, 1) means counting how many rows are in the first column.
So, the above VBA code will take us to the last row of the Excel sheet.
Step 5: If we are in the last cell of the sheet to go to the last used row, we will press the Ctrl + Up Arrow keys.
In VBA, we need to use the end key and up, i.e., End VBA xlUpVBA XLUP is a range and property method for locating the last row of a data set in an excel table. This snippet works similarly to the ctrl + down arrow shortcut commonly used in Excel worksheets.read more
Code:
Sub Last_Row_Example2() Dim LR As Long 'For understanding LR = Last Row LR = Cells(Rows.Count, 1).End(xlUp) End Sub
Step 6: It will take us to the last used row from the bottom. Now, we need the row number of this. So, use the property ROW to get the row number.
Code:
Sub Last_Row_Example2() Dim LR As Long 'For understanding LR = Last Row LR = Cells(Rows.Count, 1).End(xlUp).Row End Sub
Step 7: Now, the variable holds the last used row number. Show the value of this variable in the message box in the VBA codeVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
Code:
Sub Last_Row_Example2() Dim LR As Long 'For understanding LR = Last Row LR = Cells(Rows.Count, 1).End(xlUp).Row MsgBox LR End Sub
Run this code using the F5 key or manually. It will display the last used row.
Output:
The last used row in this worksheet is 13.
Now, we will delete one more line, run the code, and see the dynamism of the code.
Now, the result automatically takes the last row.
That is what the dynamic VBA last row code is.
As we showed in the earlier example, change the row number from a numeric value to LR.
Code:
Sub Last_Row_Example2() Dim LR As Long 'For understanding LR = Last Row LR = Cells(Rows.Count, 1).End(xlUp).Row Range("D2").Value = WorksheetFunction.Sum(Range("B2:B" & LR)) End Sub
We have removed B13 and added the variable name LR.
Now, it does not matter how many rows you add. It will automatically take the updated reference.
Method #2
We can also find the last row in VBA using the Range objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more and special VBA cells propertyCells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells.read more.
Code:
Sub Last_Row_Example3() Dim LR As Long LR = Range("A:A").SpecialCells(xlCellTypeLastCell).Row MsgBox LR End Sub
The code also gives you the last used row. For example, look at the below worksheet image.
If we run the code manually or use the F5 key result will be 12 because 12 is the last used row.
Output:
Now, we will delete the 12th row and see the result.
Even though we have deleted one row, it still shows the result as 12.
To make this code work, we must hit the “Save” button after every action. Then this code will return accurate results.
We have saved the workbook and now see the result.
Method #3
We can find the VBA last row in the used range. For example, the below code also returns the last used row.
Code:
Sub Last_Row_Example4() Dim LR As Long LR = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row MsgBox LR End Sub
It will also return the last used row.
Output:
Recommended Articles
This article has been a guide to VBA Last Row. Here, we learn the top 3 methods to find the last used row in a given column, along with examples and downloadable templates. Below are some useful articles related to VBA: –
- How to Record Macros in VBA Excel?
- Create VBA Loops
- ListObjects in VBA
Содержание
- 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
- Vba excel end xldown row
- Примеры кода
- Скачать
- Типовые задачи
- Перебор ячеек диапазона (вариант 4)
- Работа с текущей областью
- Определение границ текущей области
- Выделение столбцов / строк текущей области
- Сброс форматирования диапазона
- Поиск последней строки столбца (вариант 1)
- Поиск последней строки столбца (вариант 2)
- Поиск «последней» ячейки листа
- Разбор клипо-генератора
- VBA Last Row
- Excel VBA Last Row
- Table of contents
- How to Find the Last Used Row in the Column?
- Method #1
- Method #2
- Method #3
- Recommended Articles
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.
Источник
Vba excel end xldown row
Продолжаем наш разговор про объект Excel Range , начатый в первой части. Разберём ещё несколько типовых задач и одну развлекательную. Кстати, в процессе написания второй части я дополнил и расширил первую, поэтому рекомендую её посмотреть ещё раз.
Примеры кода
Скачать
Типовые задачи
Перебор ячеек диапазона (вариант 4)
Для коллекции добавил четвёртый вариант перебора ячеек. Как видите, можно выбирать, как перебирается диапазон — по столбцам или по строкам. Обратите внимание на использование свойства коллекции Cells . Не путайте: свойство Cells рабочего листа содержит все ячейки листа, а свойство Cells диапазона ( Range ) содержит ячейки только этого диапазона. В данном случае мы получаем все ячейки столбца или строки.
Должен вас предупредить, что код, который вы видите в этом цикле статей — это код, написанный для целей демонстрации работы с объектной моделью Excel. Тут нет объявлений переменных, обработки ошибок и проверки условий, так как я специально минимизирую программы, пытаясь акцентировать ваше внимание целиком на обсуждаемом предмете — объекте Range .
Работа с текущей областью
Excel умеет автоматически определять текущую область вокруг активной ячейки. Соответствующая команда на листе вызывается через Ctrl + A . Через ActiveCell мы посредством свойства Worksheet легко выходим на лист текущей ячейки, а уже через него можем эксплуатировать свойство UsedRange , которое и является ссылкой на Range текущей области. Чтобы понять, какой диапазон мы получили, мы меняем цвет ячеек. Функция GetRandomColor не является стандартной, она определена в модуле файла примера.
Определение границ текущей области
Демонстрируем определение левого верхнего и правого нижнего углов диапазона текущей области. С левым верхним углом всё просто, так как координаты этой ячейки всегда доступны через свойства Row и Column объекта Range (не путать с коллекциями Rows и Columns !). А вот для определения второго угла приходится использовать конструкцию вида .Rows(.Rows.Count).Row , где .Rows.Count — количество строк в диапазоне UsedRange , .Rows(.Rows.Count) — это мы получили последнюю строку, и уже для этого диапазона забираем из свойства Row координату строки. Со столбцом — по аналогии. Также обратите внимание на использование оператора With . Как видите, оператор With , помимо сокращения кода, также позволяет отказаться от объявления отдельной объектной переменной через оператор Set , что очень удобно.
Выделение столбцов / строк текущей области
Тут нет ничего нового, мы всё это обсудили в предыдущем примере. Мы получаем ссылки на столбцы / строки, меняя их цвет для контроля результата работы кода.
Сброс форматирования диапазона
Для возвращения диапазона к каноническому стерильному состоянию очень просто и удобно использовать свойство Style , и присвоить ему имя стиля «Normal». Интересно, что все остальные стандартные стили в локализованном офисе имеют русские имена, а у этого стиля оставили англоязычное имя, что неплохо.
Поиск последней строки столбца (вариант 1)
Range имеет 2 свойства EntireColumn и EntireRow , возвращающие столбцы / строки, на которых расположился ваш диапазон, но возвращают их ЦЕЛИКОМ. То есть, если вы настроили диапазон на D5 , то Range(«D5»).EntireColumn вернёт вам ссылку на D:D , а EntireRow — на 5:5 .
Идём далее — свойство End возвращает вам ближайшую ячейку в определенном направлении, стоящую на границе непрерывного диапазона с данными. Как это работает вы можете увидеть, нажимая на листе комбинации клавиш Ctrl + стрелки . Кстати, это одна из самых полезных горячих клавиш в Excel. Направление задаётся стандартными константами xlUp , xlDown , xlToRight , xlToLeft .
Классическая задача у Excel программиста — определить, где кончается таблица или, в данном случае, конкретный столбец. Идея состоит в том, чтобы встать на последнюю ячейку столбца (строка 1048576) и, стоя в этой ячейке, перейти по Ctrl + стрелка вверх (что на языке VBA — End(xlUp) ).
Поиск последней строки столбца (вариант 2)
Ещё один вариант.
Поиск «последней» ячейки листа
Тут показывается, как найти на листе ячейку, ниже и правее которой находятся только пустые ячейки. Соответственно данные надо искать в диапазоне от A1 до этой ячейки. На эту ячейку можно перейти через Ctrl + End . Как этим воспользоваться в VBA показано ниже:
Разбор клипо-генератора
Ну, и в качестве развлечения и разрядки взгляните на код клипо-генератора, который генерирует цветные квадраты в заданных границах экрана. На некоторых это оказывает умиротворяющий эффект 🙂
По нашей теме в коде обращает на себя внимание использование свойства ReSize объекта Range . Как не трудно догадаться, свойство расширяет (усекает) текущий диапазон до указанных границ, при этом левый верхний угол диапазона сохраняет свои координаты. А также посмотрите на 2 последние строчки кода, реализующие очистку экрана. Там весьма показательно использован каскад свойств End и Offset .
Источник
VBA Last Row
In VBA, when we have to find the last row, there are many different methods. The most commonly used method is the End(XLDown) method. Other methods include finding the last value using the find function in VBA, End(XLDown). The row is the easiest way to get to the last row.
Excel VBA Last Row
If writing the code is your first progress in VBA, then making the code dynamic is your next step. Excel is full of cell references Excel Is Full Of Cell References Cell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1. read more . The moment we refer to the cell, it becomes fixed. If our data increases, we need to go back to the cell reference and change the references to make the result up to date.
For an example, look at the below code.
Code:
The above code says in D2 cell value should be the summation of Range (“B2:B7”).
Now, we will add more values to the list.
Now, if we run the code, it will not give us the updated result. Rather, it still sticks to the old range, i.e., Range (“B2: B7”).
That is where dynamic code is very important.
Finding the last used row in the column is crucial in making the code dynamic. This article will discuss finding the last row in Excel VBA.
Table of contents
How to Find the Last Used Row in the Column?
Below are the examples to find the last used row in Excel VBA.
Method #1
Before we explain the code, we want you to remember how you go to the last row in the normal worksheet.
We will use the shortcut key Ctrl + down arrow.
It will take us to the last used row before any empty cell. We will also use the same VBA method to find the last row.
Step 1: Define the variable as LONG.
Code:
Step 2: We will assign this variable’s last used row number.
Code:
Step 3: Write the code as CELLS (Rows.Count,
Code:
Step 4: Now, mention the column number as 1.
Code:
CELLS(Rows.Count, 1) means counting how many rows are in the first column.
So, the above VBA code will take us to the last row of the Excel sheet.
Step 5: If we are in the last cell of the sheet to go to the last used row, we will press the Ctrl + Up Arrow keys.
Code:
Step 6: It will take us to the last used row from the bottom. Now, we need the row number of this. So, use the property ROW to get the row number.
Code:
Code:
Run this code using the F5 key or manually. It will display the last used row.
Output:
The last used row in this worksheet is 13.
Now, we will delete one more line, run the code, and see the dynamism of the code.
Now, the result automatically takes the last row.
That is what the dynamic VBA last row code is.
As we showed in the earlier example, change the row number from a numeric value to LR.
Code:
We have removed B13 and added the variable name LR.
Now, it does not matter how many rows you add. It will automatically take the updated reference.
Method #2
Code:
The code also gives you the last used row. For example, look at the below worksheet image.
If we run the code manually or use the F5 key result will be 12 because 12 is the last used row.
Output:
Now, we will delete the 12th row and see the result.
Even though we have deleted one row, it still shows the result as 12.
To make this code work, we must hit the “Save” button after every action. Then this code will return accurate results.
We have saved the workbook and now see the result.
Method #3
We can find the VBA last row in the used range. For example, the below code also returns the last used row.
Code:
It will also return the last used row.
Output:
Recommended Articles
This article has been a guide to VBA Last Row. Here, we learn the top 3 methods to find the last used row in a given column, along with examples and downloadable templates. Below are some useful articles related to VBA: –
Источник
In this VBA Tutorial, you learn how to find the last row or column with macros.
This VBA Last Row or Last Column Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Use the following Table of Contents to navigate to the section you’re interested in.
Related Excel VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below:
- General VBA constructs and structures:
- Learn the basics about working with macros and VBA here.
- Learn the basic terms you should know to start working with VBA here.
- Learn how to enable or disable macros here.
- Learn how to work with the Visual Basic Editor (VBE) here.
- Learn how to work with Sub procedures here.
- Learn how to work with Function procedures (User-Defined Functions) here.
- Learn how to refer to objects here.
- Learn how to refer to cell ranges with VBA here.
- Learn how to work with R1C1-style references here.
- Learn how to work with VBA properties here.
- Learn how to work with VBA methods here.
- Learn how to declare and work with variables here.
- Learn how to work with VBA data types here.
- Learn how to use worksheet functions in VBA here.
- Learn how to work with loops here.
- Practical VBA applications and macro examples:
- Learn how to check if a cell is empty with VBA here.
- Learn how to insert rows with VBA here.
- Learn how to delete rows with VBA here.
- Learn how to delete blank or empty rows with VBA here.
- Learn how to delete columns with VBA here.
- Learn how to hide or unhide rows and columns with VBA here.
- Learn how to create named ranges with VBA here.
- Learn how to work with VBA message boxes here.
You can also:
- Find additional VBA and Macro Tutorials here.
- Find online courses about VBA and macros here.
- Find books about VBA and macros here.
- Find Excel tools and templates here.
#1: Find the Last Row in a Column Before an Empty Cell
VBA Code to Find the Last Row in a Column Before an Empty Cell
To find the last row in a column before an empty cell with VBA, use a statement with the following structure:
LastRow = CellInColumn.End(xlDown).Row
Process to Find the Last Row in a Column Before an Empty Cell
To find the last row in a column before an empty cell with VBA, follow these steps:
- Identify a cell in the column whose last row (before an empty cell) you want to find (CellInColumn). This cell should be located above the empty cell.
- Move down the column to the end of the region (End(xlDown)). This takes you to the cell immediately above the empty cell.
- Obtain the row number of that last cell immediately above the empty cell (Row).
- Assign the number of the last row to a variable (LastRow = …).
VBA Statement Explanation
Item: LastRow
Variable of the Long data type to which you assign the number of the last row found by the macro (CellInColumn.End(xlDown).Row).
Item: =
The assignment operator (=) assigns the number of the last row found by the macro (CellInColumn.End(xlDown).Row) to LastRow.
Item: CellInColumn
Range object representing a cell in the column whose last row (before an empty cell) you want to find. The cell represented by Range should be located above the empty cell.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: End(xlDown)
The Range.End property returns a Range object representing the cell at the end of the region containing the source range (CellInColumn).
When searching for the last row in a column (before an empty cell), set the Direction parameter of the Range.End property to xlDown. xlDown specifies the direction in which to move (down).
CellInColumn.End(xlDown) is the equivalent to pressing the “Ctrl+Down Arrow” keyboard shortcut when CellInColumn is the active cell.
Item: Row
The Range.Row property returns the number of the first row of the first area in the source range.
When searching for the last row in a column (before an empty cell), the source range is the cell immediately above that empty cell (CellInColumn.End(xlDown)). Therefore, the Range.Row property returns the number of that row immediately above the applicable empty cell.
Macro Example to Find the Last Row in a Column Before an Empty Cell
The following macro (User-Defined Function) example finds the last row (before an empty cell) in the column containing the cell passed as argument (myCell).
Function lastRowInColumnBeforeBlank(myCell As Range) As Long 'Source: https://powerspreadsheets.com/ 'finds the last row (before an empty cell) in the column containing myCell 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'find the last row (before an empty cell) in the column containing myCell lastRowInColumnBeforeBlank = myCell.End(xlDown).Row End Function
Effects of Executing Macro Example to Find the Last Row in a Column Before an Empty Cell
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (16) of the last row before an empty cell (A17) in the column containing the cell passed as argument (A6).
#2: Find the Last Row Among Several Columns Before Empty Cells
VBA Code to Find the Last Row Among Several Columns Before Empty Cells
To find the last row (furthest down, before empty cells) among several columns with VBA, use a macro with the following statement structure:
OverallLastRow = 0 With Range For Counter = .Column To .Columns(.Columns.Count).Column ColumnLastRow = .Parent.Cells(.Row, Counter).End(xlDown).Row If ColumnLastRow > OverallLastRow Then OverallLastRow = ColumnLastRow Next Counter End With
Process to Find the Last Row Among Several Columns Before Empty Cells
To find the last row (furthest down, before empty cells) among several columns with VBA, follow these steps:
- Initialize the variable that will hold the number of the overall (across all columns) last row by setting it to 0 (OverallLastRow = 0).
- Identify a cell range containing cells in the (several) columns you consider when searching for the last row before empty cells (With Range | End With). This cell range should begin above the empty cells.
- Loop through each column in Range (For Counter = .Column To .Columns(.Columns.Count).Column | Next Counter).
- Identify a cell in the column you’re currently working with (.Parent.Cells(.Row, Counter)).
- Move down the column to the end of the region (End(xlDown)). This takes you to the cell immediately above the empty cell in that column.
- Obtain the row number of that last cell immediately above the empty cell (Row).
- Assign the number of the last row in the column you’re working with to a variable (ColumnLastRow = …).
- Test if the number of the last row in the column you’re working with (ColumnLastRow) is larger than the value currently held by the variable (OverallLastRow) that holds the overall (across all columns) last row number (If ColumnLastRow > OverallLastRow).
- If the number of the last row in the column you’re working with (ColumnLastRow) is larger than the value currently held by the variable (OverallLastRow) that holds the overall (across all columns) last row number, update the value held by the variable (Then OverallLastRow = ColumnLastRow).
VBA Statement Explanation
Line #1: OverallLastRow = 0
OverallLastRow is a variable of the Long data type to which you assign the number of the last row (among several columns) found by the macro.
The assignment operator (=) initializes OverallLastRow by assigning the value of 0.
Lines #2 and #7: With Range| End With
The With… End With statement executes a series of statements (lines #3 through #6) on a single object (Range).
Range is a Range object representing a cell range containing cells in the (several) columns you consider when searching for the last row (before empty cells). This cell range should begin above those empty cells.
You can usually work with, among others, the Worksheet.Range property to refer to this Range object.
Lines #3 and #6: For Counter = .Column To .Columns(.Columns.Count).Column | Next Counter
Item: For Counter = … To … | Next Counter
The For… Next statement repeats a group of statements (lines #4 and #5) a specific number of times (.Column To .Columns(.Columns.Count).Column).
Counter is the loop counter. If you explicitly declare a variable to represent Counter, you can usually declare it as of the Long data type.
The following are the initial and final values of Counter:
- Initial value: The number of the first column in Range (.Column).
- Final value: The number of the last column in Range (.Columns(.Columns.Count).Column).
Therefore, the For… Next statement loops through all the columns in Range.
Item: .Column
The Range.Column property returns the number of the first column of the first area in the source range (Range).
When searching for the last row among several columns (before empty cells), you use the Range.Column property twice, as follows:
- .Column returns the number of the first column in Range.
- .Columns(.Columns.Count).Column returns the number of the last column in Range.
Item: .Columns(.Columns.Count)
The Range.Columns property returns a Range object representing the columns in the source range (Range).
The Range.Count property returns the number of objects in a collection. When searching for the last row among several columns (before empty cells), the Range.Count property returns the number of columns in the source range (.Columns).
Therefore:
- .Columns returns a Range object representing all columns in Range.
- .Columns.Count returns the number of columns in Range.
.Columns.Count is used as an index number of the Range.Columns property (.Columns(.Columns.Count)). In other words, .Columns(.Columns.Count) refers to the column (within Range) whose index number is equal to the number of columns in Range (.Columns.Count). This is the last column in Range.
Line #4: ColumnLastRow = .Parent.Cells(.Row, Counter).End(xlDown).Row
Item: ColumnLastRow
Variable of the Long data type to which you assign the number of the last row in the current column (column number Counter) found by the macro (.Parent.Cells(.Row, Counter).End(xlDown).Row).
Item: =
The assignment operator (=) assigns the number of the last row found by the macro in the current column (.Parent.Cells(.Row, Counter).End(xlDown).Row) to ColumnLastRow.
Item: Parent
The Range.Parent property returns the parent object of the source range (Range).
When searching for the last row among several columns, the Range.Parent property returns a Worksheet object representing the worksheet that contains Range.
Item: Cells(.Row, Counter)
The Worksheet.Cells property returns a Range object representing all the cells in the worksheet. If you specify the row and column index, the Worksheet.Cells property returns a Range object representing the cell at the intersection of the specified row and column.
When searching for the last row among several columns (before empty cells):
- .Row is the row index. The Range.Row property returns the number of the first row of the first area in the source range (Range).
- Counter is the column index and loop counter of the For… Next statement that iterates through all the columns in Range.
Therefore, the Worksheet.Cells property returns a Range object representing the cell at the intersection of:
- The first row of Range (.Row); and
- The column through which the For… Next loop is currently iterating (Counter).
Item: End(xlDown)
The Range.End property returns a Range object representing the cell at the end of the region containing the source range (Cells(.Row, Counter)).
When searching for the last row among several columns (before empty cells), set the Direction parameter of the Range.End property to xlDown. xlDown specifies the direction in which to move (down).
.Parent.Cells(.Row, Counter).End(xlDown) is the equivalent to pressing the “Ctrl+Down Arrow” keyboard shortcut when .Parent.Cells(.Row, Counter) is the active cell.
Item: Row
The Range.Row property returns the number of the first row of the first area in the source range.
When searching for the last row in a column (column number Counter, before an empty cell), the source range is the cell immediately above that empty cell (.Parent.Cells(.Row, Counter).End(xlDown)). Therefore, the Range.Row property returns the number of that row immediately above the applicable empty cell.
Line #5: If ColumnLastRow > OverallLastRow Then OverallLastRow = ColumnLastRow
Item: If … Then …
The If… Then… statement conditionally executes a group of statements (OverallLastRow = ColumnLastRow), depending on the value of an expression (ColumnLastRow > OverallLastRow).
Item: ColumnLastRow > OverallLastRow
Condition of the If… Then… statement, which evaluates to True or False as follows:
- True if ColumnLastRow is larger than (>) OverallLastRow.
- False otherwise.
Item: OverallLastRow = ColumnLastRow
Statement that is executed if the condition tested by the If… Then… statement (ColumnLastRow > OverallLastRow) returns True.
The assignment operator (=) assigns the value held by ColumnLastRow to OverallLastRow.
Macro Example to Find the Last Row Among Several Columns Before Empty Cells
The following macro (User-Defined Function) example finds the last row (before empty cells) among the columns containing the cell range passed as argument (myRange).
Function lastRowInSeveralColumnsBeforeBlank(myRange As Range) As Long 'Source: https://powerspreadsheets.com/ 'finds the last row (before empty cells) in the columns containing myRange 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'declare variables to represent loop counter and hold value of last row in current column Dim iCounter As Long Dim iColumnLastRow As Long 'initialize variable that holds the number of the (overall) last row across several columns lastRowInSeveralColumnsBeforeBlank = 0 With myRange 'loop through each column in myRange For iCounter = .Column To .Columns(.Columns.Count).Column 'find last row (before an empty cell) in the current column iColumnLastRow = .Parent.Cells(.Row, iCounter).End(xlDown).Row 'if the number of the last row in the current column is larger than the row number held by lastRowInSeveralColumnsBeforeBlank, update value held by lastRowInSeveralColumnsBeforeBlank If iColumnLastRow > lastRowInSeveralColumnsBeforeBlank Then lastRowInSeveralColumnsBeforeBlank = iColumnLastRow Next iCounter End With End Function
Effects of Executing Macro Example to Find the Last Row Among Several Columns Before Empty Cells
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (17) of the last row before empty cells (A14, B15, C16, D17, E18) among the columns containing the cell range passed as argument (A6 to E6).
#3: Find the Last Row in a Column
VBA Code to Find the Last Row in a Column
To find the last row in a column with VBA, use a macro with the following statement structure:
With CellInColumn.Parent LastRow = .Cells(.Rows.Count, CellInColumn.Column).End(xlUp).Row End With
Process to Find the Last Row in a Column
To find the last row in a column with VBA, follow these steps:
- Identify a cell in the column whose last row you want to find (CellInColumn) and the worksheet containing this cell (CellInColumn.Parent).
- Identify the last worksheet cell in the column containing CellInColumn (.Cells(.Rows.Count, CellInColumn.Column)).
- Move up the column to the end of the region (End(xlUp)). This takes you to the last cell in the column.
- Obtain the row number of that last cell in the column (Row).
- Assign the number of the last row to a variable (LastRow = …).
VBA Statement Explanation
Lines #1 and #3: With CellInColumn.Parent | End With
Item: With … | End With
The With… End With statement executes a series of statements (line #2) on a single object (CellInColumn.Parent).
Item: CellInColumn
Range object representing a cell in the column whose last row you want to find.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Parent
The Range.Parent property returns the parent object of the source range (CellInColumn).
When searching for the last row in a column, the Range.Parent property returns a Worksheet object representing the worksheet that contains CellInColumn.
Line #2: LastRow = .Cells(.Rows.Count, CellInColumn.Column).End(xlUp).Row
Item: LastRow
Variable of the Long data type to which you assign the number of the last row found by the macro (.Cells(.Rows.Count, CellInColumn.Column).End(xlUp).Row).
Item: =
The assignment operator (=) assigns the number of the last row found by the macro (.Cells(.Rows.Count, CellInColumn.Column).End(xlUp).Row) to LastRow.
Item: .Cells(.Rows.Count, CellInColumn.Column)
The Worksheet.Cells property returns a Range object representing all the cells in the worksheet. If you specify the row and column index, the Worksheet.Cells property returns a Range object representing the cell at the intersection of the specified row and column.
When searching for the last row in a column:
- .Rows.Count is the row index and returns the number of the last row in the worksheet (CellInColumn.Parent). For these purposes:
- The Worksheet.Rows property returns a Range object representing all rows on the worksheet (CellInColumn.Parent).
- The Range.Count property returns the number of objects in a collection. When searching for the last row in a column, the Range.Count property returns the number of rows in the worksheet (CellInColumn.Parent).
- CellInColumn.Column is the column index and returns the number of the column containing CellInColumn. For these purposes, the Range.Column property returns the number of the first column of the first area in the source range (CellInColumn).
Therefore, the Worksheet.Cells property returns a Range object representing the cell at the intersection of:
- The last row of the worksheet (.Rows.Count); and
- The column containing CellInColumn (CellInColumn.Column).
Item: End(xlUp)
The Range.End property returns a Range object representing the cell at the end of the region containing the source range (.Cells(.Rows.Count, CellInColumn.Column)).
When searching for the last row in a column, set the Direction parameter of the Range.End property to xlUp. xlUp specifies the direction in which to move (up).
.Cells(.Rows.Count, CellInColumn.Column).End(xlUp) is the equivalent to pressing the “Ctrl+Up Arrow” keyboard shortcut when Cells(.Rows.Count, CellInColumn.Column) is the active cell.
Item: Row
The Range.Row property returns the number of the first row of the first area in the source range.
When searching for the last row in a column, the source range is the last cell in the column (.Cells(.Rows.Count, CellInColumn.Column).End(xlUp)). Therefore, the Range.Row property returns the number of that last row.
Macro Example to Find the Last Row in a Column
The following macro (User-Defined Function) example finds the last row in the column containing the cell passed as argument (myCell).
Function lastRowInColumn(myCell As Range) As Long 'Source: https://powerspreadsheets.com/ 'finds the last row in the column containing myCell 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'identify worksheet containing myCell With myCell.Parent 'find the last row in the column containing myCell lastRowInColumn = .Cells(.Rows.Count, myCell.Column).End(xlUp).Row End With End Function
Effects of Executing Macro Example to Find the Last Row in a Column
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (25) of the last row in the column containing the cell passed as argument (A6).
#4: Find the Last Row Among Several Columns
VBA Code to Find the Last Row Among Several Columns
To find the last row (furthest down) among several columns with VBA, use a macro with the following statement structure:
OverallLastRow = 0 With Range For Counter = .Column To .Columns(.Columns.Count).Column With .Parent ColumnLastRow = .Cells(.Rows.Count, Counter).End(xlUp).Row If ColumnLastRow > OverallLastRow Then OverallLastRow = ColumnLastRow End With Next Counter End With
Process to Find the Last Row Among Several Columns
To find the last row (furthest down) among several columns with VBA, follow these steps:
- Initialize the variable that will hold the number of the overall (across all columns) last row by setting it to 0 (OverallLastRow = 0).
- Identify a cell range containing cells in the (several) columns you consider when searching for the last row (With Range | End With).
- Loop through each column in Range (For Counter = .Column To .Columns(.Columns.Count).Column | Next Counter).
- Identify the worksheet containing Range (With .Parent | End With).
- Identify the last worksheet cell in the column you’re currently working with (.Cells(.Rows.Count, Counter)).
- Move up the column to the end of the region (End(xlUp)). This takes you to the last cell in the column.
- Obtain the row number of that last cell in the column (Row).
- Assign the number of the last row in the column you’re working with to a variable (ColumnLastRow = …).
- Test if the number of the last row in the column you’re working with (ColumnLastRow) is larger than the value currently held by the variable (OverallLastRow) that holds the overall (across all columns) last row number (If ColumnLastRow > OverallLastRow).
- If the number of the last row in the column you’re working with (ColumnLastRow) is larger than the value currently held by the variable (OverallLastRow) that holds the overall (across all columns) last row number, update the value held by the variable (Then OverallLastRow = ColumnLastRow).
VBA Statement Explanation
Line #1: OverallLastRow = 0
OverallLastRow is a variable of the Long data type to which you assign the number of the last row among several columns found by the macro.
The assignment operator (=) initializes OverallLastRow by assigning the value of 0.
Lines #2 and #9: With Range | End With
The With… End With statement executes a series of statements (lines #3 through #8) on a single object (Range).
Range is a Range object representing a cell range containing cells in the (several) columns you consider when searching for the last row.
You can usually work with, among others, the Worksheet.Range property to refer to this Range object.
Lines #3 and #8: For Counter = .Column To .Columns(.Columns.Count).Column | Next Counter
Item: For Counter = … To … | Next Counter
The For… Next statement repeats a group of statements (lines #4 to #7) a specific number of times (.Column To .Columns(.Columns.Count).Column).
Counter is the loop counter. If you explicitly declare a variable to represent Counter, you can usually declare it as of the Long data type.
The following are the initial and final values of Counter:
- Initial value: The number of the first column in Range (.Column).
- Final value: The number of the last column in Range (.Columns(.Columns.Count).Column).
Therefore, the For… Next statement loops through all the columns in Range.
Item: .Column
The Range.Column property returns the number of the first column of the first area in the source range (Range).
When searching for the last row among several columns, you use the Range.Column property twice, as follows:
- .Column returns the number of the first column in Range.
- .Columns(.Columns.Count).Column returns the number of the last column in Range.
Item: .Columns(.Columns.Count).Column
The Range.Columns property returns a Range object representing the columns in the source range (Range).
The Range.Count property returns the number of objects in a collection. When searching for the last row among several columns, the Range.Count property returns the number of columns in the source range (.Columns).
Therefore:
- .Columns returns a Range object representing all columns in Range.
- .Columns.Count returns the number of columns in Range.
.Columns.Count is used as an index number of the Range.Columns property (.Columns(.Columns.Count)). In other words, .Columns(.Columns.Count) refers to the column (within Range) whose index number is equal to the number of columns in Range (.Columns.Count). This is the last column in Range.
Lines #4 and #7: With .Parent | End With
The With… End With statement executes a series of statements (lines #5 and #6) on a single object (.Parent).
The Range.Parent property returns the parent object of the source range (Range). When searching for the last row among several columns, the Range.Parent property returns a Worksheet object representing the worksheet that contains Range.
Line #5: ColumnLastRow = .Cells(.Rows.Count, Counter).End(xlUp).Row
Item: ColumnLastRow
Variable of the Long data type to which you assign the number of the last row in the current column (column number Counter) found by the macro (.Cells(.Rows.Count, Counter).End(xlUp).Row).
Item: =
The assignment operator (=) assigns the number of the last row found by the macro in the current column (.Cells(.Rows.Count, Counter).End(xlUp).Row) to ColumnLastRow.
Item: .Cells(.Rows.Count, Counter)
The Worksheet.Cells property returns a Range object representing all the cells in the worksheet. If you specify the row and column index, the Worksheet.Cells property returns a Range object representing the cell at the intersection of the specified row and column.
When searching for the last row among several columns:
- .Rows.Count is the row index and returns the number of the last row in the worksheet (Range.Parent). For these purposes:
- The Worksheet.Rows property returns a Range object representing all rows on the worksheet (Range.Parent).
- The Range.Count property returns the number of objects in a collection. When searching for the last row among several columns, the Range.Count property returns the number of rows in the worksheet (Range.Parent).
- Counter is the column index and loop counter of the For… Next statement that iterates through all the columns in Range.
Therefore, the Worksheet.Cells property returns a Range object representing the cell at the intersection of:
- The last row of the worksheet (.Rows.Count); and
- The column through which the For… Next loop is currently iterating (Counter).
Item: End(xlUp)
The Range.End property returns a Range object representing the cell at the end of the region containing the source range (.Cells(.Rows.Count, Counter)).
When searching for the last row among several columns, set the Direction parameter of the Range.End property to xlUp. xlUp specifies the direction in which to move (up).
.Cells(.Rows.Count, Counter).End(xlUp) is the equivalent to pressing the “Ctrl+Up Arrow” keyboard shortcut when .Cells(.Rows.Count, Counter) is the active cell.
Item: Row
The Range.Row property returns the number of the first row of the first area in the source range.
When searching for the last row in a column (column number Counter), the source range is the last cell in the column (.Cells(.Rows.Count, Counter).End(xlUp)). Therefore, the Range.Row property returns the number of that last row.
Line #6: If ColumnLastRow > OverallLastRow Then OverallLastRow = ColumnLastRow
Item: If … Then
The If… Then… statement conditionally executes a group of statements (OverallLastRow = ColumnLastRow), depending on the value of an expression (ColumnLastRow > OverallLastRow).
Item: ColumnLastRow > OverallLastRow
Condition of the If… Then… statement, which evaluates to True or False as follows:
- True if ColumnLastRow is larger than (>) OverallLastRow.
- False otherwise.
Item: OverallLastRow = ColumnLastRow
Statement that is executed if the condition tested by the If… Then… statement (ColumnLastRow > OverallLastRow) returns True.
The assignment operator (=) assigns the value held by ColumnLastRow to OverallLastRow.
Macro Example to Find the Last Row Among Several Columns
The following macro (User-Defined Function) example finds the last row among the columns containing the cell range passed as argument (myRange).
Function lastRowInSeveralColumns(myRange As Range) As Long 'Source: https://powerspreadsheets.com/ 'finds the last row in the columns containing myRange 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'declare variables to represent loop counter and hold value of last row in current column Dim myColumnLastRow As Long Dim iCounter As Long 'initialize variable that holds the number of the (overall) last row across several columns lastRowInSeveralColumns = 0 With myRange 'loop through each column in myRange For iCounter = .Column To .Columns(.Columns.Count).Column 'work with the worksheet containing myRange With .Parent 'find last row in the current column myColumnLastRow = .Cells(.Rows.Count, iCounter).End(xlUp).Row 'if the number of the last row in the current column is larger than the row number held by lastRowInSeveralColumns, update value held by lastRowInSeveralColumns If myColumnLastRow > lastRowInSeveralColumns Then lastRowInSeveralColumns = myColumnLastRow End With Next iCounter End With End Function
Effects of Executing Macro Example to Find the Last Row Among Several Columns
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (25) of the last row among the columns containing the cell range passed as argument (A6 to E6).
#5: Find the Last Row by Going to the Last Cell in the Used Range
VBA Code to Find the Last Row by Going to the Last Cell in the Used Range
To find the last row by going to the last cell in the used range with VBA, use a macro with the following structure:
Worksheet.UsedRange LastRow = Worksheet.Cells.SpecialCells(xlCellTypeLastCell).Row
Process to Find the Last Row by Going to the Last Cell in the Used Range
To find the last row by going to the last cell in the used range with VBA, follow these steps:
- Identify the worksheet whose last row you want to find (Worksheet).
- Attempt to reset the used range of Worksheet (Worksheet.UsedRange).
- Identify the last cell in the used range of Worksheet (Worksheet.Cells.SpecialCells(xlCellTypeLastCell)).
- Obtain the row number of that last cell in the used range (Row).
- Assign the number of the last row to a variable (LastRow = …).
VBA Statement Explanation
Line #1: Worksheet.UsedRange
Item: Worksheet
Worksheet object representing the worksheet whose last row (in the used range) you want to find.
You can usually work with, among others, the following properties to refer to this Worksheet object:
- Application.ActiveSheet.
- Workbook.Worksheets.
Item: UsedRange
The Worksheet.UsedRange property returns a Range object representing the used range of Worksheet.
From a broad perspective, you can think of the used range as the cell range encompassing all “used” cells within a worksheet.
Working with the Worksheet.UsedRange property can be tricky. One of the main challenges associated with relying on this property is that Excel retains cells that aren’t longer in use (but have been) and considers them when calculating the used range.
Therefore, prior to using VBA code that relies on Excel’s calculation of the used range, you may want to (try to) reset it. The following 2 alternative statements are commonly used for these purposes:
'alternative #1 (used in this Tutorial) Worksheet.UsedRange 'alternative #2 (relies on the Range.Count property) rowsCount = Worksheet.UsedRange.Rows.Count
There are cases in which these used-range-resetting statements fail.
Line #2: LastRow = Worksheet.Cells.SpecialCells(xlCellTypeLastCell).Row
Item: LastRow
Variable of the Long data type to which you assign the number of the last row found by the macro (Worksheet.Cells.SpecialCells(xlCellTypeLastCell).Row).
Item: =
The assignment operator (=) assigns the number of the last row found by the macro (Worksheet.Cells.SpecialCells(xlCellTypeLastCell).Row) to LastRow.
Item: Worksheet
Worksheet object representing the worksheet whose last row (in the used range) you want to find. This worksheet should be the same whose used range you attempt to reset (line #1).
You can usually work with, among others, the following properties to refer to this Worksheet object:
- Application.ActiveSheet.
- Workbook.Worksheets.
Item: Cells
The Worksheet.Cells property returns a Range object representing all the cells in Worksheet.
Item: SpecialCells(xlCellTypeLastCell)
The Range.SpecialCells method returns a Range object representing the cells that match a specific type and value.
When Searching for the last row by going to the last cell in the used range, set the Type parameter of the Range.SpecialCells method to the xlCellTypeLastCell built-in constant (or 11). This results in Range.SpecialCells returning a Range object that represents the last cell in the used range.
Item: Row
The Range.Row property returns the number of the first row of the first area in the source range.
When searching for the last row by going to the last cell in the used range, the source range is that last cell of the used range (Worksheet.Cells.SpecialCells(xlCellTypeLastCell)). Therefore, the Range.Row property returns the number of that last row.
Macro Example to Find the Last Row by Going to the Last Cell in the Used Range
The following macro example finds the last row in the active sheet (ActiveSheet) by going to the last cell in the used range (Cells.SpecialCells(xlCellTypeLastCell)).
Sub lastRowInWorksheetXlCellTypeLastCell() 'Source: https://powerspreadsheets.com/ 'finds the last row in the active sheet's used range 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'declare variable to hold value of last row Dim myLastRow As Long 'attempt to reset the active sheet's used range ActiveSheet.UsedRange 'find the last row in the active sheet by, previously, identifying the last cell in the used range myLastRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row 'display the number of the last row found by the macro MsgBox myLastRow End Sub
Effects of Executing Macro Example to Find the Last Row by Going to the Last Cell in the Used Range
The following image illustrates the effects of using the macro example. As expected, Excel returns the number (26) of the last row in the active sheet by going to the last cell in the used range. Excel considers formatting (including conditional formatting) when keeping track of a worksheet’s used range.
#6: Find the Last Row in the Used Range
VBA Code to Find the Last Row in the Used Range
To find the last row in the used range with VBA, use a macro with the following statement structure:
Worksheet.UsedRange With Worksheet.UsedRange LastRow = .Rows(.Rows.Count).Row End With
Process to Find the Last Row in the Used Range
To find the last row in the used range with VBA, follow these steps:
- Identify the worksheet whose last row you want to find (Worksheet).
- Attempt to reset the used range of Worksheet (Worksheet.UsedRange).
- Work with the used range of Worksheet (With Worksheet.UsedRange | End With).
- Identify the last row in the used range of Worksheet (.Rows(.Rows.Count)).
- Obtain the number of that last row in the used range (Row).
- Assign the number of the last row to a variable (LastRow = …).
VBA Statement Explanation
Line #1: Worksheet.UsedRange
Item: Worksheet
Worksheet object representing the worksheet whose last row (in the used range) you want to find.
You can usually work with, among others, the following properties to refer to this Worksheet object:
- Application.ActiveSheet.
- Workbook.Worksheets.
Item: UsedRange
The Worksheet.UsedRange property returns a Range object representing the used range of Worksheet.
From a broad perspective, you can think of the used range as the cell range encompassing all “used” cells within a worksheet.
Working with the Worksheet.UsedRange property can be tricky. One of the main challenges associated with relying on this property is that Excel retains cells that aren’t longer in use (but have been) and considers them when calculating the used range.
Therefore, prior to using VBA code that relies on Excel’s calculation of the used range, you may want to (try to) reset it. The following 2 alternative statements are commonly used for these purposes:
'alternative #1 (used in this Tutorial) Worksheet.UsedRange 'alternative #2 (relies on the Range.Count property) rowsCount = Worksheet.UsedRange.Rows.Count
There are cases in which these used-range-resetting statements fail.
Lines #2 and #4: With Worksheet.UsedRange | End With
Item: With … | End With
The With… End With statement executes a series of statements (line #3) on a single object (Worksheet.UsedRange).
Item: Worksheet
Worksheet object representing the worksheet whose last row (in the used range) you want to find. This worksheet should be the same whose used range you attempt to reset (line #1).
You can usually work with, among others, the following properties to refer to this Worksheet object:
- Application.ActiveSheet.
- Workbook.Worksheets.
Item: UsedRange
The Worksheet.UsedRange property returns a Range object representing the used range of Worksheet. From a broad perspective, you can think of the used range as the cell range encompassing all “used” cells within a worksheet.
Line #3: LastRow = .Rows(.Rows.Count).Row
Item: LastRow
Variable of the Long data type to which you assign the number of the last row found by the macro (.Rows(.Rows.Count).Row).
Item: =
The assignment operator (=) assigns the number of the last row found by the macro (.Rows(.Rows.Count).Row) to LastRow.
Item: .Rows(.Rows.Count)
The Range.Rows property returns a Range object representing the rows in the source range (Worksheet.UsedRange).
The Range.Count property returns the number of objects in a collection. When searching for the last row in the used range, the Range.Count property returns the number of rows in the source range (.Rows).
Therefore:
- .Rows returns a Range object representing all rows in Worksheet.UsedRange.
- .Rows.Count returns the number of rows in Worksheet.UsedRange.
.Rows.Count is used as an index number of the Range.Rows property (.Rows(.Rows.Count)). In other words, .Rows(.Rows.Count) refers to the row (within Worksheet.UsedRange) whose index number is equal to the number of rows in Worksheet.UsedRange (.Rows.Count). This is the last row in Worksheet.UsedRange.
Item: Row
The Range.Row property returns the number of the first row of the first area in the source range.
When searching for the last row in the used range, the source range is that last row in the used range (.Rows(.Rows.Count)). Therefore, the Range.Row property returns the number of that last row.
Macro Example to Find the Last Row in the Used Range
The following macro example finds the last row in the used range of the active sheet (ActiveSheet.UsedRange).
Sub lastRowInWorksheetUsedRange() 'Source: https://powerspreadsheets.com/ 'finds the last row in the active sheet's used range 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'declare variable to hold value of last row Dim myLastRow As Long 'attempt to reset the active sheet's used range ActiveSheet.UsedRange 'find the last row in the active sheet's used range With ActiveSheet.UsedRange myLastRow = .Rows(.Rows.Count).Row End With 'display the number of the last row found by the macro MsgBox myLastRow End Sub
Effects of Executing Macro Example to Find the Last Row in the Used Range
The following image illustrates the effects of using the macro example. As expected, Excel returns the number (26) of the last row in the active sheet’s used range. Excel considers formatting (including conditional formatting) when keeping track of a worksheet’s used range.
#7: Find the Last Row by Searching
VBA Code to Find the Last Row by Searching
To find the last row by searching with VBA, use a macro with the following statement structure:
If Application.CountA(Range) = 0 Then LastRow = 0 Else LastRow = Range.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row End If
Process to Find the Last Row by Searching
To find the last row by searching with VBA, follow these steps:
- Identify the cell range whose last row you want to find (Range).
- Test if Range is empty (If Application.CountA(Range) = 0).
- If Range is empty (Then), handle this situation by, for example, assigning the value of 0 to the variable that will hold the number of the last row (LastRow = 0).
- If Range isn’t empty (Else), search for the last cell in Range containing any character sequence (Range.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious)).
- Obtain the row number of that last cell containing any character sequence (Row).
- Assign the number of the last row to the appropriate variable (LastRow = …).
VBA Statement Explanation
Lines #1, #3 and #5: If Application.CountA(Range) = 0 Then | Else | End If
Item: If … Then | Else | End If
The If… Then… Else statement conditionally executes a group of statements (line #2 or line #4), depending on the value of an expression (Application.CountA(Range) = 0).
Item: Application.CountA(Range) = 0
Condition of the If… Then… Else statement, which evaluates to True or False as follows:
- True if all cells in Range are empty. For these purposes:
- Range is a Range object representing the cell range whose last row you want to find. You can usually work with, among others, the Worksheet.Range or Worksheet.Cells properties to refer to this Range object.
- The WorksheetFunction.CountA method (Application.CountA(Range)) counts the number of cells within Range that are not empty.
- False if at least 1 cell in Range isn’t empty.
In other words, this condition tests whether Range is empty (Application.CountA(Range) = 0) or not.
Line #2: LastRow = 0
Statement that is executed if the condition tested by the If… Then… Else statement (Application.CountA(Range) = 0) returns True.
LastRow is a variable of the Long data type to which you assign the number of the last row found by the macro.
If Range is empty (Application.CountA(Range) = 0), use the assignment operator (=) to assign an appropriate value (LastRow = 0 assigns the value of 0) to LastRow. In other words, use this statement (or set of statements) to handle the cases where Range is empty.
Line #4: LastRow = Range.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Item: LastRow
Variable of the Long data type to which you assign the number of the last row found by the macro (Range.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row).
Item: =
The assignment operator (=) assigns the number of the last row found by the macro (Range.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row) to LastRow.
Item: Range
Range object representing the cell range whose last row you want to find.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
The Range.Find method:
- Finds specific information in a cell range (Range); and
- Returns a Range object representing the first cell where the information is found.
When identifying the last row by searching, set the parameters of the Range.Find method as follows:
- What, which represents the data to search for, to “*” (What:=”*”). The asterisk (*) acts as a wildcard and results in Range.Find searching for any character sequence.
- LookIn, which specifies the type of data to search, to the xlFormulas built-in constant (or -4123) which refers to formulas (LookIn:=xlFormulas).
- LookAt, which specifies whether the match is made against the whole or any part of the search text, to the xlPart built-in constant (or 2) which matches against any part of the search text (LookAt:=xlPart).
- SearchOrder, which specifies the order in which to search the cell range, to the xlByRows built-in constant (or 1) which searches across a row and then moves to the next row (SearchOrder:=xlByRows).
- SearchDirection, which specifies the search direction, to the xlPrevious built-in constant (or 2) which searches for the previous match in the cell range (SearchDirection:=xlPrevious).
The settings for LookIn, LookAt, SearchOrder and MatchByte (used only if you have selected or installed double-byte language support) are saved every time you work with the Range.Find method. Therefore, if you don’t specify values for these parameters when searching for the last row, the saved values are used. Setting these parameters changes the settings in the Find dialog box and, vice-versa, changing the settings in the Find dialog box changes these parameters. Therefore, to reduce the risk of errors, set these arguments explicitly when searching for the last row.
Item: Row
The Range.Row property returns the number of the first row of the first area in the source range.
When identifying the last row by searching, the source range is the Range object returned by the Range.Find method (Range.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious)). This Range object represents the last cell (furthest down) in the cell range you work with (Range). Therefore, the Range.Row property returns the number of that last row.
Macro Example to Find the Last Row by Searching
The following macro (User-Defined Function) example finds the last row in the cell range passed as argument (myRange) by searching. If myRange is empty (Application.CountA(myRange) = 0), the User-Defined Function returns the number 0 (lastRowRangeFind = 0).
Function lastRowRangeFind(myRange As Range) As Long 'Source: https://powerspreadsheets.com/ 'finds the last row in myRange by searching for the last cell with any character sequence. If myRange is empty, assigns the 0 as the number of the last row 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'test if myRange is empty If Application.CountA(myRange) = 0 Then 'if myRange is empty, assign 0 to lastRowRangeFind lastRowRangeFind = 0 Else 'if myRange isn't empty, find the last cell with any character sequence (What:="*") by: '(1) Searching for the previous match (SearchDirection:=xlPrevious); '(2) Across rows (SearchOrder:=xlByRows) lastRowRangeFind = myRange.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row End If End Function
Effects of Executing Macro Example to Find the Last Row by Searching
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (25) of the last row in the cell range passed as argument (A5 to E26) by searching.
#8: Find the Last Row in the Current Region
VBA Code to Find the Last Row in the Current Region
To find the last row in the current region with VBA, use a macro with the following statement structure:
With Cell.CurrentRegion LastRow = .Rows(.Rows.Count).Row End With
Process to Find the Last Row in the Current Region
To find the last row in the current region with VBA, follow these steps:
- Identify the current region whose last row you want to find (With Cell.CurrentRegion | End With).
- Identify the last row in the current region (.Rows(.Rows.Count)).
- Obtain the number of that last row in the current region (Row).
- Assign the number of the last row to a variable (LastRow = …).
VBA Statement Explanation
Lines #1 and #3: With Cell.CurrentRegion | End With
Item: With … | End With
The With… End With statement executes a series of statements (line #2) on a single object (Cell.CurrentRegion).
Item: Cell
Range object representing a cell in the current region whose last row you want to find.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: CurrentRegion
The Range.CurrentRegion property returns a Range object representing the current region. The current region is a cell range bounded by a combination of:
- Blank rows; and
- Blank columns.
The Range.CurrentRegion property (basically) expands from Cell to include the entire current region.
Line #2: LastRow = .Rows(.Rows.Count).Row
Item: LastRow
Variable of the Long data type to which you assign the number of the last row found by the macro (.Rows(.Rows.Count).Row).
Item: =
The assignment operator (=) assigns the number of the last row found by the macro (.Rows(.Rows.Count).Row) to LastRow.
Item: .Rows(.Rows.Count)
The Range.Rows property returns a Range object representing the rows in the source range (Cell.CurrentRegion).
The Range.Count property returns the number of objects in a collection. When searching for the last row in the current region, the Range.Count property returns the number of rows in the source range (.Rows).
Therefore:
- .Rows returns a Range object representing all rows in Cell.CurrentRegion.
- .Rows.Count returns the number of rows in Cell.CurrentRegion.
.Rows.Count is used as an index number of the Range.Rows property (.Rows(.Rows.Count)). In other words, .Rows(.Rows.Count) refers to the row (within Cell.CurrentRegion) whose index number is equal to the number of rows in Cell.CurrentRegion (.Rows.Count). This is the last row in Cell.CurrentRegion.
Item: Row
The Range.Row property returns the number of the first row of the first area in the source range.
When searching for the last row in the current region, the source range is that last row of that current region (.Rows(.Rows.Count)). Therefore, the Range.Row property returns the number of that last row.
Macro Example to Find the Last Row in the Current Region
The following macro example finds the last row in the current region (myCell.CurrentRegion) containing cell A6 in the active worksheet (ActiveSheet.Range(“A6”)).
Sub lastRowInCurrentRegion() 'Source: https://powerspreadsheets.com/ 'finds the last row in the current region containing cell A6 in the active worksheet 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'declare object variable to represent source range Dim myCell As Range 'declare variable to hold value of last row Dim myLastRow As Long 'identify source range Set myCell = ActiveSheet.Range("A6") 'identify the current region containing myCell With myCell.CurrentRegion 'find the last row in the current region containing myCell myLastRow = .Rows(.Rows.Count).Row End With 'display the number of the last row found by the macro MsgBox myLastRow End Sub
Effects of Executing Macro Example to Find the Last Row in the Current Region
The following image illustrates the effects of using the macro example. As expected, Excel returns the number (25) of the last row in the current region containing cell A6.
#9: Find the Last Row in an Excel Table
VBA Code to Find the Last Row in an Excel Table
To find the last row in an Excel Table with VBA, use a macro with the following statement structure:
With ExcelTable.Range LastRow = .Rows(.Rows.Count).Row End With
Process to Find the Last Row in an Excel Table
To find the last row in an Excel Table with VBA, follow these steps:
- Identify the Excel Table whose last row you want to find (With ExcelTable.Range | End With).
- Identify the last row in the Excel Table (.Rows(.Rows.Count)).
- Obtain the number of that last row in the Excel Table (Row).
- Assign the number of the last row to a variable (LastRow = …).
VBA Statement Explanation
Lines #1 and #3: With ExcelTable.Range | End With
Item: With … | End With
The With… End With statement executes a series of statements (line #2) on a single object (ExcelTable.Range).
Item: ExcelTable
ListObject object representing the Excel Table whose last row you want to find.
You can usually work with the Worksheet.ListObjects property to refer to this ListObject object.
Item: Range
The ListObject.Range property returns a Range object representing the cell range to which ExcelTable applies.
Line #2: LastRow = .Rows(.Rows.Count).Row
Item: LastRow
Variable of the Long data type to which you assign the number of the last row found by the macro (.Rows(.Rows.Count).Row).
Item: =
The assignment operator (=) assigns the number of the last row found by the macro (.Rows(.Rows.Count).Row) to LastRow.
Item: .Rows(.Rows.Count)
The Range.Rows property returns a Range object representing the rows in the source range (ExcelTable.Range).
The Range.Count property returns the number of objects in a collection. When searching for the last row in an Excel Table, the Range.Count property returns the number of rows in the source range (.Rows).
Therefore:
- .Rows returns a Range object representing all rows in ExcelTable.Range.
- .Rows.Count returns the number of rows in ExcelTable.Range.
.Rows.Count is used as an index number of the Range.Rows property (.Rows(.Rows.Count)). In other words, .Rows(.Rows.Count) refers to the row (within ExcelTable.Range) whose index number is equal to the number of rows in ExcelTable.Range (.Rows.Count). This is the last row in ExcelTable.Range.
Item: Row
The Range.Row property returns the number of the first row of the first area in the source range.
When searching for the last row in an Excel Table, the source range is that last row of the Excel Table (.Rows(.Rows.Count)). Therefore, the Range.Row property returns the number of that last row.
Macro Example to Find the Last Row in an Excel Table
The following macro (User-Defined Function) example finds the last row in an Excel Table (ListObjects(myTableIndex).Range):
- Located in the same worksheet as that where the User-Defined Function is used in a worksheet formula (Application.Caller.Parent); and
- Whose index number is passed as argument of the User-Defined Function (myTableIndex).
Function lastRowInTable(myTableIndex As Long) As Long 'Source: https://powerspreadsheets.com/ 'finds the last column in an Excel Table (in the same worksheet as that where the User-Defined Function is used and whose index number is myTableIndex) 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'identify the cell range containing the Excel Table located in the same worksheet as that where the User-Defined Function is used and whose index number is myTableIndex With Application.Caller.Parent.ListObjects(myTableIndex).Range 'find the last row in the Excel Table lastRowInTable = .Rows(.Rows.Count).Row End With End Function
Effects of Executing Macro Example to Find the Last Row in an Excel Table
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (25) of the last row in the Excel Table whose index number (1) is passed as argument.
#10: Find the Last Row in a Named Cell Range
VBA Code to Find the Last Row in a Named Cell Range
To find the last row in a named cell range with VBA, use a macro with the following statement structure:
With NamedRange LastRow = .Rows(.Rows.Count).Row End With
Process to Find the Last Row in a Named Cell Range
To find the last row in a named cell range with VBA, follow these steps:
- Identify the named cell range whose last row you want to find (With NamedRange | End With).
- Identify the last row in the named cell range (.Rows(.Rows.Count)).
- Obtain the number of that last row in the named cell range (Row).
- Assign the number of the last row to a variable (LastRow = …).
VBA Statement Explanation
Lines #1 and #3: With NamedRange | End With
The With… End With statement executes a series of statements (line #2) on a single object (NamedRange).
NamedRange is a Range object representing the named cell range whose last row you want to find. You can usually work with the Worksheet.Range property to refer to this Range object.
Line #2: LastRow = .Rows(.Rows.Count).Row
Item: LastRow
Variable of the Long data type to which you assign the number of the last row found by the macro (.Rows(.Rows.Count).Row).
Item: =
The assignment operator (=) assigns the number of the last row found by the macro (.Rows(.Rows.Count).Row) to LastRow.
Item: .Rows(.Rows.Count)
The Range.Rows property returns a Range object representing the rows in the source range (NamedRange).
The Range.Count property returns the number of objects in a collection. When searching for the last row in a named cell range, the Range.Count property returns the number of rows in the source range (.Rows).
Therefore:
- .Rows returns a Range object representing all rows in NamedRange.
- .Rows.Count returns the number of rows in NamedRange.
.Rows.Count is used as an index number of the Range.Rows property (.Rows(.Rows.Count)). In other words, .Rows(.Rows.Count) refers to the row (within NamedRange) whose index number is equal to the number of rows in NamedRange (.Rows.Count). This is the last row in NamedRange.
Item: Row
The Range.Row property returns the number of the first row of the first area in the source range.
When searching for the last row in a named cell range, the source range is the last row of that named cell range (.Rows(.Rows.Count)). Therefore, the Range.Row property returns the number of that last row.
Macro Example to Find the Last Row in a Named Cell Range
The following macro (User-Defined Function) example finds the last row in a named cell range (Range(myRangeName)):
- Located in the same worksheet as that where the User-Defined Function is used in a worksheet formula (Application.Caller.Parent); and
- Whose name is passed as argument of the User-Defined Function (myRangeName).
Function lastRowInNamedRange(myRangeName As String) As Long 'Source: https://powerspreadsheets.com/ 'finds the last row in a named cell range (in the same worksheet as that where the User-Defined Function is used and whose name is myRangeName) 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'identify the named cell range whose name is myRangeName With Application.Caller.Parent.Range(myRangeName) 'find the last row in myRangeName lastRowInNamedRange = .Rows(.Rows.Count).Row End With End Function
Effects of Executing Macro Example to Find the Last Row in a Named Cell Range
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (25) of the last row in the named cell range passed as argument (namedRangeRow).
#11: Find the Last Column in a Row Before an Empty Cell
VBA Code to Find the Last Column in a Row Before an Empty Cell
To find the last column in a row before an empty cell with VBA, use a statement with the following structure:
LastColumn = CellInRow.End(xlToRight).Column
Process to Find the Last Column in a Row Before an Empty Cell
To find the last column in a row before an empty cell with VBA, follow these steps:
- Identify a cell in the row whose last row (before an empty cell) you want to find (CellInRow). This cell should be located to the left of the empty cell.
- Move to the right of the row to the end of the region (End(xlToRight)). This takes you to the cell immediately before (to the left of) the empty cell.
- Obtain the column number of that last cell immediately before the empty cell (Column).
- Assign the number of the last column to a variable (LastColumn = …).
VBA Statement Explanation
Item: LastColumn
Variable of the Long data type to which you assign the number of the last column found by the macro (CellInRow.End(xlToRight).Column).
Item: =
The assignment operator (=) assigns the number of the last column found by the macro (CellInRow.End(xlToRight).Column) to LastColumn.
Item: CellInRow
Range object representing a cell in the row whose last column (before an empty cell) you want to find. The cell represented by Range should be located to the left of the empty cell.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: End(xlToRight)
The Range.End property returns a Range object representing the cell at the end of the region containing the source range (CellInRow).
When searching for the last column in a row (before an empty cell), set the Direction parameter of the Range.End property to xlToRight. xlToRight specifies the direction in which to move (right).
CellInRow.End(xlToRight) is the equivalent to pressing the “Ctrl+Right Arrow” keyboard shortcut when CellInRow is the active cell.
Item: Column
The Range.Column property returns the number of the first column of the first area in the source range.
When searching for the last column in a row (before an empty cell), the source range is the cell immediately to the left of that empty cell (CellInRow.End(xlToRight)). Therefore, the Range.Column property returns the number of that column immediately before (to the left of) the applicable empty cell.
Macro Example to Find the Last Column in a Row Before an Empty Cell
The following macro (User-Defined Function) example finds the last column (before an empty cell) in the row containing the cell passed as argument (myCell).
Function lastColumnInRowBeforeBlank(myCell As Range) As Long 'Source: https://powerspreadsheets.com/ 'finds the last column (before an empty cell) in the row containing myCell 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'find the last column (before an empty cell) in the row containing myCell lastColumnInRowBeforeBlank = myCell.End(xlToRight).Column End Function
Effects of Executing Macro Example to Find the Last Column in a Row Before an Empty Cell
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (2) of the last column before an empty cell (C6) in the column containing the cell passed as argument (A6).
#12: Find the Last Column Among Several Rows Before Empty Cells
VBA Code to Find the Last Column Among Several Rows Before Empty Cells
To find the last column (furthest to the right, before empty cells) among several rows with VBA, use a macro with the following statement structure:
OverallLastColumn = 0 With Range For Counter = .Row To .Rows(.Rows.Count).Row RowLastColumn = .Parent.Cells(Counter, .Column).End(xlToRight).Column If RowLastColumn > OverallLastColumn Then OverallLastColumn = RowLastColumn Next Counter End With
Process to Find the Last Column Among Several Rows Before Empty Cells
To find the last column (furthest to the right, before empty cells) among several rows with VBA, follow these steps:
- Initialize the variable that will hold the number of the overall (across all rows) last column by setting it to 0 (OverallLastColumn = 0).
- Identify a cell range containing cells in the (several) rows you consider when searching for the last column before empty cells (With Range | End With). This cell range should begin to the left of the empty cells.
- Loop through each row in Range (For Counter = .Row To .Rows(.Rows.Count).Row | Next Counter).
- Identify a cell in the row you’re currently working with (.Parent.Cells(Counter, .Column)).
- Move to the right of the row to the end of the region (End(xlToRight)). This takes you to the cell immediately before (to the left of) the empty cell in that row.
- Obtain the column number of that last cell immediately before the empty cell (Column).
- Assign the number of the last column in the row you’re working with to a variable (RowLastColumn = …).
- Test if the number of the last column in the row you’re working with (RowLastColumn) is larger than the value currently held by the variable (OverallLastColumn) that holds the overall (across all rows) last column number (If RowLastColumn > OverallLastColumn).
- If the number of the last column in the row you’re working with (RowLastColumn) is larger than the value currently held by the variable (OverallLastColumn) that holds the overall (across all rows) last column number, update the value held by the variable (Then OverallLastColumn = RowLastColumn).
VBA Statement Explanation
Line #1: OverallLastColumn = 0
OverallLastColumn is a variable of the Long data type to which you assign the number of the last column (among several rows) found by the macro.
The assignment operator (=) initializes OverallLastColumn by assigning the value of 0.
Lines #2 and #7: With Range | End With
The With… End With statement executes a series of statements (lines #3 through #6) on a single object (Range).
Range is a Range object representing a cell range containing cells in the (several) rows you consider when searching for the last column (before empty cells). This cell range should begin to the left of those empty cells.
You can usually work with, among others, the Worksheet.Range property to refer to this Range object.
Lines #3 and #6: For Counter = .Row To .Rows(.Rows.Count).Row | Next Counter
Item: For Counter = … To … | Next Counter
The For… Next statement repeats a group of statements (lines #4 and #5) a specific number of times (.Row To .Rows(.Rows.Count).Row).
Counter is the loop counter. If you explicitly declare a variable to represent Counter, you can usually declare it as of the Long data type.
The following are the initial and final values of Counter:
- Initial value: The number of the first row in Range (.Row).
- Final value: The number of the last row in Range (.Rows(.Rows.Count).Row).
Therefore, the For… Next statement loops through all the rows in Range.
Item: .Row
The Range.Row property returns the number of the first row of the first area in the source range (Range).
When searching for the last column among several rows (before empty cells), you use the Range.Row property twice, as follows:
- .Row returns the number of the first row in Range.
- .Rows(.Rows.Count).Row returns the number of the last row in Range.
Item: .Rows(.Rows.Count).Row
The Range.Rows property returns a Range object representing the rows in the source range (Range).
The Range.Count property returns the number of objects in a collection. When searching for the last column among several rows (before empty cells), the Range.Count property returns the number of rows in the source range (.Rows).
Therefore:
- .Rows returns a Range object representing all rows in Range.
- .Rows.Count returns the number of rows in Range.
.Rows.Count is used as an index number of the Range.Rows property (.Rows(.Rows.Count)). In other words, .Rows(.Rows.Count) refers to the row (within Range) whose index number is equal to the number of rows in Range (.Rows .Count). This is the last row in Range.
Line #4: RowLastColumn = .Parent.Cells(Counter, .Column).End(xlToRight).Column
Item: RowLastColumn
Variable of the Long data type to which you assign the number of the last column in the current row (row number Counter) found by the macro (.Parent.Cells(Counter, .Column).End(xlToRight).Column).
Item: =
The assignment operator (=) assigns the number of the last column found by the macro in the current row (.Parent.Cells(Counter, .Column).End(xlToRight).Column) to RowLastColumn.
Item: Parent
The Range.Parent property returns the parent object of the source range (Range).
When searching for the last column among several rows, the Range.Parent property returns a Worksheet object representing the worksheet that contains Range.
Item: Cells(Counter, .Column)
The Worksheet.Cells property returns a Range object representing all the cells in the worksheet. If you specify the row and column index, the Worksheet.Cells property returns a Range object representing the cell at the intersection of the specified row and column.
When searching for the last column among several rows (before empty cells):
- Counter is the row index and loop counter of the For… Next statement that iterates through all the rows in Range.
- .Column is the column index. The Range.Column property returns the number of the first column of the first area in the source range (Range).
Therefore, the Worksheet.Cells property returns a Range object representing the cell at the intersection of:
- The row through which the For… Next loop is currently iterating (Counter); and
- The first column of Range (.Column).
Item: End(xlToRight)
The Range.End property returns a Range object representing the cell at the end of the region containing the source range (Cells(Counter, .Column)).
When searching for the last column among several rows (before empty cells), set the Direction parameter of the Range.End property to xlToRight. xlToRight specifies the direction in which to move (right).
.Parent.Cells(Counter, .Column).End(xlToRight) is the equivalent to pressing the “Ctrl+Right Arrow” keyboard shortcut when .Parent.Cells(Counter, .Column) is the active cell.
Item: Column
The Range.Column property returns the number of the first column of the first area in the source range.
When searching for the last column in a row (row number Counter, before an empty cell), the source range is the cell immediately to the left of that empty cell (.Parent.Cells(Counter, .Column).End(xlToRight)). Therefore, the Range.Column property returns the number of that column immediately before (to the left of) the applicable empty cell.
Line #5: If RowLastColumn > OverallLastColumn Then OverallLastColumn = RowLastColumn
Item: If … Then …
The If… Then… statement conditionally executes a group of statements (OverallLastColumn = RowLastColumn), depending on the value of an expression (RowLastColumn > OverallLastColumn).
Item: RowLastColumn > OverallLastColumn
Condition of the If… Then… statement, which evaluates to True or False as follows:
- True if RowLastColumn is larger than (>) OverallLastColumn.
- False otherwise.
Item: OverallLastColumn = RowLastColumn
Statement that is executed if the condition tested by the If… Then… statement (RowLastColumn > OverallLastColumn) returns True.
The assignment operator (=) assigns the value held by RowLastColumn to OverallLastColumn.
Macro Example to Find the Last Column Among Several Rows Before Empty Cells
The following macro (User-Defined Function) example finds the last column (before empty cells) among the rows containing the cell range passed as argument (myRange).
Function lastColumnInSeveralRowsBeforeBlank(myRange As Range) As Long 'Source: https://powerspreadsheets.com/ 'finds the last column (before empty cells) in the rows containing myRange 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'declare variables to represent loop counter and hold value of last column in current row Dim iCounter As Long Dim myRowLastColumn As Long 'initialize variable that holds the number of the (overall) last column across several rows lastColumnInSeveralRowsBeforeBlank = 0 With myRange 'loop through each row in myRange For iCounter = .Row To .Rows(.Rows.Count).Row 'find last column (before an empty cell) in the current row myRowLastColumn = .Parent.Cells(iCounter, .Column).End(xlToRight).Column 'if the number of the last column in the current row is larger than the column number held by lastColumnInSeveralRowsBeforeBlank, update value held by lastColumnInSeveralRowsBeforeBlank If myRowLastColumn > lastColumnInSeveralRowsBeforeBlank Then lastColumnInSeveralRowsBeforeBlank = myRowLastColumn Next iCounter End With End Function
Effects of Executing Macro Example to Find the Last Column Among Several Rows Before Empty Cells
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (5) of the last column before empty cells (column F) among the columns containing the cell range passed as argument (A6 to A25).
#13: Find the Last Column in a Row
VBA Code to Find the Last Column in a Row
To find the last column in a row with VBA, use a macro with the following statement structure:
With CellInRow.Parent LastColumn = .Cells(CellInRow.Row, .Columns.Count).End(xlToLeft).Column End With
Process to Find the Last Column in a Row
To find the last column in a row with VBA, follow these steps:
- Identify a cell in the row whose last column you want to find (CellInRow) and the worksheet containing this cell (CellInRow.Parent).
- Identify the last worksheet cell in the row containing CellInRow (.Cells(CellInRow.Row, .Columns.Count)).
- Move towards the left of the row to the end of the region (End(xlToLeft)). This takes you to the last cell in the row.
- Obtain the column number of that last cell in the row (Column).
- Assign the number of the last column to a variable (LastColumn = …).
VBA Statement Explanation
Lines #1 and #3: With CellInRow.Parent | End With
Item: With … | End With
The With… End With statement executes a series of statements (line #2) on a single object (CellInRow.Parent).
Item: CellInRow.
Range object representing a cell in the row whose last column you want to find.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Parent
The Range.Parent property returns the parent object of the source range (CellInRow).
When searching for the last column in a row, the Range.Parent property returns a Worksheet object representing the worksheet that contains CellInRow.
Line #2: LastColumn = .Cells(CellInRow.Row, .Columns.Count).End(xlToLeft).Column
Item: LastColumn
Variable of the Long data type to which you assign the number of the last column found by the macro (.Cells(CellInRow.Row, .Columns.Count).End(xlToLeft).Column).
Item: =
The assignment operator (=) assigns the number of the last column found by the macro (.Cells(CellInRow.Row, .Columns.Count).End(xlToLeft).Column) to LastColumn.
Item: .Cells(CellInRow.Row, .Columns.Count)
The Worksheet.Cells property returns a Range object representing all the cells in the worksheet. If you specify the row and column index, the Worksheet.Cells property returns a Range object representing the cell at the intersection of the specified row and column.
When searching for the last column in a row:
- CellInRow.Row is the row index and returns the number of the row containing CellInRow. For these purposes, the Range.Row property returns the number of the first row of the first area in the source range (CellInRow).
- .Columns.Count is the column index and returns the number of the last column in the worksheet (CellInRow.Parent). For these purposes:
- The Worksheet.Columns property returns a Range object representing all columns on the worksheet (CellInRow.Parent).
- The Range.Count property returns the number of objects in a collection. When searching for the last column in a row, the Range.Count property returns the number of columns in the worksheet (CellInColumn.Parent).
Therefore, the Worksheet.Cells property returns a Range object representing the cell at the intersection of:
- The row containing CellInRow (CellInRow.Row); and
- The last column of the worksheet (.Columns.Count).
Item: End(xlToLeft)
The Range.End property returns a Range object representing the cell at the end of the region containing the source range (.Cells(CellInRow.Row, .Columns.Count)).
When searching for the last column in a row, set the Direction parameter of the Range.End property to xlToLeft. xlToLeft specifies the direction in which to move (left).
.Cells(CellInRow.Row, .Columns.Count).End(xlToLeft) is the equivalent to pressing the “Ctrl+Left Arrow” keyboard shortcut when .Cells(CellInRow.Row, .Columns.Count) is the active cell.
Item: Column
The Range.Column property returns the number of the first column of the first area in the source range.
When searching for the last column in a row, the source range is the last cell in the row (.Cells(CellInRow.Row, .Columns.Count).End(xlToLeft)). Therefore, the Range.Column property returns the number of that last column.
Macro Example to Find the Last Column in a Row
The following macro (User-Defined Function) example finds the last column in the row containing the cell passed as argument (myCell).
Function lastColumnInRow(myCell As Range) As Long 'Source: https://powerspreadsheets.com/ 'finds the last column in the row containing myCell 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'identify worksheet containing myCell With myCell.Parent 'find the last column in the row containing myCell lastColumnInRow = .Cells(myCell.Row, .Columns.Count).End(xlToLeft).Column End With End Function
Effects of Executing Macro Example to Find the Last Column in a Row
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (5) of the last column in the column containing the cell passed as argument (A7).
#14: Find the Last Column Among Several Rows
VBA Code to Find the Last Column Among Several Rows
To find the last column (furthest to the right) among several columns with VBA, use a macro with the following statement structure:
OverallLastColumn = 0 With Range For Counter = .Row To .Rows(.Rows.Count).Row With .Parent RowLastColumn = .Cells(Counter, .Columns.Count).End(xlToLeft).Column If RowLastColumn > OverallLastColumn Then OverallLastColumn = RowLastColumn End With Next Counter End With
Process to Find the Last Column Among Several Rows
To find the last column (furthest to the right) among several columns with VBA, follow these steps:
- Initialize the variable that will hold the number of the overall (across all rows) last column by setting it to 0 (OverallLastColumn = 0).
- Identify a cell range containing cells in the (several) rows you consider when searching for the last column (With Range | End With).
- Loop through each row in Range (For Counter = .Row To .Rows(.Rows.Count).Row | Next Counter).
- Identify the worksheet containing Range (With .Parent | End With).
- Identify the last worksheet cell in the row you’re currently working with (.Cells(Counter, .Columns.Count)).
- Move towards the left of the row to the end of the region (End(xlToLeft)). This takes you to the last cell in the row.
- Obtain the column number of that last cell in the row (Column).
- Assign the number of the last column in the row you’re working with to a variable (RowLastColumn = …).
- Test if the number of the last column in the row you’re working with (RowLastColumn) is larger than the value currently held by the variable (OverallLastColumn) that holds the overall (across all rows) last column number (If RowLastColumn > OverallLastColumn).
- If the number of the last column in the row you’re working with (RowLastColumn) is larger than the value currently held by the variable (OverallLastColumn) that holds the overall (across all rows) last column number, update the value held by the variable (Then OverallLastColumn = RowLastColumn).
VBA Statement Explanation
Line #1: OverallLastColumn = 0
OverallLastColumn is a variable of the Long data type to which you assign the number of the last column among several rows found by the macro.
The assignment operator (=) initializes OverallLastColumn by assigning the value of 0.
Lines #2 and #9: With Range | End With
The With… End With statement executes a series of statements (lines #3 through #8) on a single object (Range).
Range is a Range object representing a cell range containing cells in the (several) rows you consider when searching for the last column.
You can usually work with, among others, the Worksheet.Range property to refer to this Range object.
Lines #3 and #8: For Counter = .Row To .Rows(.Rows.Count).Row | Next Counter
Item: For Counter = … To … | Next Counter
The For… Next statement repeats a group of statements (lines #4 to #7) a specific number of times (.Row To .Rows(.Rows.Count).Row).
Counter is the loop counter. If you explicitly declare a variable to represent Counter, you can usually declare it as of the Long data type.
The following are the initial and final values of Counter:
- Initial value: The number of the first row in Range (.Row).
- Final value: The number of the last row in Range (.Rows(.Rows.Count).Row).
Therefore, the For… Next statement loops through all the rows in Range.
Item: .Row
The Range.Row property returns the number of the first row of the first area in the source range (Range).
When searching for the last column among several rows, you use the Range.Row property twice, as follows:
- .Row returns the number of the first row in Range.
- .Rows(.Rows.Count).Row returns the number of the last row in Range.
Item: .Rows(.Rows.Count).Row
The Range.Rows property returns a Range object representing the rows in the source range (Range).
The Range.Count property returns the number of objects in a collection. When searching for the last column among several rows, the Range.Count property returns the number of rows in the source range (.Rows).
Therefore:
- .Rows returns a Range object representing all rows in Range.
- .Rows.Count returns the number of rows in Range.
.Rows.Count is used as an index number of the Range.Rows property (.Rows(.Rows.Count)). In other words, .Rows(.Rows.Count) refers to the row (within Range) whose index number is equal to the number of rows in Range (.Rows.Count). This is the last row in Range.
Lines #4 and #7: With .Parent | End With
The With… End With statement executes a series of statements (lines #5 and #6) on a single object (.Parent).
The Range.Parent property returns the parent object of the source range (Range). When searching for the last column among several rows, the Range.Parent property returns a Worksheet object representing the worksheet that contains Range.
Line #5: RowLastColumn = .Cells(Counter, .Columns.Count).End(xlToLeft).Column
Item: RowLastColumn
Variable of the Long data type to which you assign the number of the last column in the current row (row number Counter) found by the macro (.Cells(Counter, .Columns.Count).End(xlToLeft).Column).
Item: =
The assignment operator (=) assigns the number of the last column found by the macro in the current row (.Cells(Counter, .Columns.Count).End(xlToLeft).Column) to RowLastColumn.
Item: .Cells(Counter, .Columns.Count)
The Worksheet.Cells property returns a Range object representing all the cells in the worksheet. If you specify the row and column index, the Worksheet.Cells property returns a Range object representing the cell at the intersection of the specified row and column.
When searching for the last column among several rows:
- Counter is the row index and loop counter of the For… Next statement that iterates through all the rows in Range.
- .Columns.Count is the column index and returns the number of the last column in the worksheet (Range.Parent). For these purposes:
- The Worksheet.Columns property returns a Range object representing all column on the worksheet (Range.Parent).
- The Range.Count property returns the number of objects in a collection. When searching for the last column among several rows, the Range.Count property returns the number of columns in the worksheet (Range.Parent).
Therefore, the Worksheet.Cells property returns a Range object representing the cell at the intersection of:
- The row through which the For… Next loop is currently iterating (Counter); and
- The last column of the worksheet (.Columns.Count).
Item: End(xlToLeft)
The Range.End property returns a Range object representing the cell at the end of the region containing the source range (.Cells(Counter, .Columns.Count)).
When searching for the last column among several rows, set the Direction parameter of the Range.End property to xlToLeft. xlToLeft specifies the direction in which to move (left).
.Cells(Counter, .Columns.Count).End(xlToLeft) is the equivalent to pressing the “Ctrl+Left Arrow” keyboard shortcut when .Cells(Counter, .Columns.Count) is the active cell.
Item: Column
The Range.Column property returns the number of the first column of the first area in the source range.
When searching for the last column in a row (row number Counter), the source range is the last cell in the row (.Cells(Counter, .Columns.Count).End(xlToLeft)). Therefore, the Range.Column property returns the number of that last column.
Line #6: If RowLastColumn > OverallLastColumn Then OverallLastColumn = RowLastColumn
Item: If … Then …
The If… Then… statement conditionally executes a group of statements (OverallLastColumn = RowLastColumn), depending on the value of an expression (RowLastColumn > OverallLastColumn).
Item: RowLastColumn > OverallLastColumn
Condition of the If… Then… statement, which evaluates to True or False as follows:
- True if RowLastColumn is larger than (>) OverallLastColumn.
- False otherwise.
Item: OverallLastColumn = RowLastColumn
Statement that is executed if the condition tested by the If… Then… statement (RowLastColumn > OverallLastColumn) returns True.
The assignment operator (=) assigns the value held by RowLastColumn to OverallLastColumn .
Macro Example to Find the Last Column Among Several Rows
The following macro (User-Defined Function) example finds the last column among the rows containing the cell range passed as argument (myRange).
Function lastColumnInSeveralRows(myRange As Range) As Long 'Source: https://powerspreadsheets.com/ 'finds the last column in the rows containing myRange 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'declare variables to represent loop counter and hold value of last column in current row Dim iCounter As Long Dim myRowLastColumn As Long 'initialize variable that holds the number of the (overall) last column across several rows lastColumnInSeveralRows = 0 With myRange 'loop through each row in myRange For iCounter = .Row To .Rows(.Rows.Count).Row 'work with the worksheet containing myRange With .Parent 'find last column in the current row myRowLastColumn = .Cells(iCounter, .Columns.Count).End(xlToLeft).Column 'if the number of the last column in the current row is larger than the column number held by lastColumnInSeveralRows, update value held by lastColumnInSeveralRows If myRowLastColumn > lastColumnInSeveralRows Then lastColumnInSeveralRows = myRowLastColumn End With Next iCounter End With End Function
Effects of Executing Macro Example to Find the Last Column Among Several Rows
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (5) of the last column among the rows containing the cell range passed as argument (A7 to A25).
#15: Find the Last Column by Going to the Last Cell in the Used Range
VBA Code to Find the Last Column by Going to the Last Cell in the Used Range
To find the last column by going to the last cell in the used range with VBA, use a macro with the following statement structure:
Worksheet.UsedRange LastColumn = Worksheet.Cells.SpecialCells(xlCellTypeLastCell).Column
Process to Find the Last Column by Going to the Last Cell in the Used Range
To find the last column by going to the last cell in the used range with VBA, follow these steps:
- Identify the worksheet whose last column you want to find (Worksheet).
- Attempt to reset the used range of Worksheet (Worksheet.UsedRange).
- Identify the last cell in the used range of Worksheet (Worksheet.Cells.SpecialCells(xlCellTypeLastCell)).
- Obtain the column number of that last cell in the used range (Column).
- Assign the number of the last column to a variable (LastColumn = …).
VBA Statement Explanation
Line #1: Worksheet.UsedRange
Item: Worksheet
Worksheet object representing the worksheet whose last column (in the used range) you want to find.
You can usually work with, among others, the following properties to refer to this Worksheet object:
- Application.ActiveSheet.
- Workbook.Worksheets.
Item: UsedRange
The Worksheet.UsedRange property returns a Range object representing the used range of Worksheet.
From a broad perspective, you can think of the used range as the cell range encompassing all “used” cells within a worksheet.
Working with the Worksheet.UsedRange property can be tricky. One of the main challenges associated with relying on this property is that Excel retains cells that aren’t longer in use (but have been) and considers them when calculating the used range.
Therefore, prior to using VBA code that relies on Excel’s calculation of the used range, you may want to (try to) reset it. The following 2 alternative statements are commonly used for these purposes:
'alternative #1 (used in this Tutorial) Worksheet.UsedRange 'alternative #2 (relies on the Range.Count property) columnsCount = Worksheet.UsedRange.Columns.Count
There are cases in which these used-range-resetting statements fail.
Line #2: LastColumn = Worksheet.Cells.SpecialCells(xlCellTypeLastCell).Column
Item: LastColumn
Variable of the Long data type to which you assign the number of the last column found by the macro (Worksheet.Cells.SpecialCells(xlCellTypeLastCell).Column).
Item: =
The assignment operator (=) assigns the number of the last column found by the macro (Worksheet.Cells.SpecialCells(xlCellTypeLastCell).Column) to LastColumn.
Item: Worksheet
Worksheet object representing the worksheet whose last column (in the used range) you want to find. This worksheet should be the same whose used range you attempt to reset (line #1).
You can usually work with, among others, the following properties to refer to this Worksheet object:
- Application.ActiveSheet.
- Workbook.Worksheets.
Item: Cells
The Worksheet.Cells property returns a Range object representing all the cells in Worksheet.
Item: SpecialCells(xlCellTypeLastCell)
The Range.SpecialCells method returns a Range object representing the cells that match a specific type and value.
When Searching for the last column by going to the last cell in the used range, set the Type parameter of the Range.SpecialCells method to the xlCellTypeLastCell built-in constant (or 11). This results in Range.SpecialCells returning a Range object that represents the last cell in the used range.
Item: Column
The Range.Column property returns the number of the first column of the first area in the source range.
When searching for the last column by going to the last cell in the used range, the source range is that last cell of the used range (Worksheet.Cells.SpecialCells(xlCellTypeLastCell)). Therefore, the Range.Column property returns the number of that last column.
Macro Example to Find the Last Column by Going to the Last Cell in the Used Range
The following macro example finds the last column in the active sheet (ActiveSheet) by going to the last cell in the used range (Cells.SpecialCells(xlCellTypeLastCell)).
Sub lastColumnInWorksheetXlCellTypeLastCell() 'Source: https://powerspreadsheets.com/ 'finds the last column in the active sheet's used range 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'declare variable to hold value of last column Dim myLastColumn As Long 'attempt to reset the active sheet's used range ActiveSheet.UsedRange 'find the last column in the active sheet by, previously, identifying the last cell in the used range myLastColumn = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column 'display the number of the last column found by the macro MsgBox myLastColumn End Sub
Effects of Executing Macro Example to Find the Last Column by Going to the Last Cell in the Used Range
The following image illustrates the effects of using the macro example. As expected, Excel returns the number (6) of the last column in the active sheet’s used range. Excel considers formatting (including conditional formatting) when keeping track of a worksheet’s used range.
#16: Find the Last Column in the Used Range
VBA Code to Find the Last Column in the Used Range
To find the last column in the used range with VBA, use a macro with the following statement structure:
Worksheet.UsedRange With Worksheet.UsedRange LastColumn = .Columns(.Columns.Count).Column End With
Process to Find the Last Column in the Used Range
To find the last column in the used range with VBA, follow these steps:
- Identify the worksheet whose last column you want to find (Worksheet).
- Attempt to reset the used range of Worksheet (Worksheet.UsedRange).
- Work with the used range of Worksheet (With Worksheet.UsedRange | End With).
- Identify the last column in the used range of Worksheet (.Columns(.Columns.Count)).
- Obtain the number of that last column in the used range (Column).
- Assign the number of the last column to a variable (Column = …).
VBA Statement Explanation
Line #1: Worksheet.UsedRange
Item: Worksheet
Worksheet object representing the worksheet whose last column (in the used range) you want to find.
You can usually work with, among others, the following properties to refer to this Worksheet object:
- Application.ActiveSheet.
- Workbook.Worksheets.
Item: UsedRange
The Worksheet.UsedRange property returns a Range object representing the used range of Worksheet.
From a broad perspective, you can think of the used range as the cell range encompassing all “used” cells within a worksheet.
Working with the Worksheet.UsedRange property can be tricky. One of the main challenges associated with relying on this property is that Excel retains cells that aren’t longer in use (but have been) and considers them when calculating the used range.
Therefore, prior to using VBA code that relies on Excel’s calculation of the used range, you may want to (try to) reset it. The following 2 alternative statements are commonly used for these purposes:
'alternative #1 (used in this Tutorial) Worksheet.UsedRange 'alternative #2 (relies on the Range.Count property) columnsCount = Worksheet.UsedRange.Columns.Count
There are cases in which these used-range-resetting statements fail.
Lines #2 and #4: With Worksheet.UsedRange | End With
Item: With … | End With
The With… End With statement executes a series of statements (line #3) on a single object (Worksheet.UsedRange).
Item: Worksheet
Worksheet object representing the worksheet whose last column (in the used range) you want to find. This worksheet should be the same whose used range you attempt to reset (line #1).
You can usually work with, among others, the following properties to refer to this Worksheet object:
- Application.ActiveSheet.
- Workbook.Worksheets.
Item: UsedRange
The Worksheet.UsedRange property returns a Range object representing the used range of Worksheet. From a broad perspective, you can think of the used range as the cell range encompassing all “used” cells within a worksheet.
Line #3: LastColumn = .Columns(.Columns.Count).Column
Item: LastColumn
Variable of the Long data type to which you assign the number of the last column found by the macro (.Columns(.Columns.Count).Column).
Item: =
The assignment operator (=) assigns the number of the last column found by the macro (.Columns(.Columns.Count).Column) to LastColumn.
Item: .Columns(.Columns.Count)
The Range.Columns property returns a Range object representing the columns in the source range (Worksheet.UsedRange).
The Range.Count property returns the number of objects in a collection. When searching for the last column in the used range, the Range.Count property returns the number of columns in the source range (.Columns).
Therefore:
- .Columns returns a Range object representing all columns in Worksheet.UsedRange.
- .Columns.Count returns the number of columns in Worksheet.UsedRange.
.Columns.Count is used as an index number of the Range.Columns property (.Columns(.Columns.Count)). In other words, .Columns(.Columns.Count) refers to the column (within Worksheet.UsedRange) whose index number is equal to the number of columns in Worksheet.UsedRange (.Columns.Count). This is the last column in Worksheet.UsedRange.
Item: Column
The Range.Column property returns the number of the first column of the first area in the source range.
When searching for the last column in the used range, the source range is that last column in the used range (.Columns(.Columns.Count)). Therefore, the Range.Column property returns the number of that last column.
Macro Example to Find the Last Column in the Used Range
The following macro example finds the last column in the used range of the active sheet (ActiveSheet.UsedRange).
Sub lastColumnInWorksheetUsedRange() 'Source: https://powerspreadsheets.com/ 'finds the last column in the active sheet's used range 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'declare variable to hold value of last column Dim myLastColumn As Long 'attempt to reset the active sheet's used range ActiveSheet.UsedRange 'find the last column in the active sheet's used range With ActiveSheet.UsedRange myLastColumn = .Columns(.Columns.Count).Column End With 'display the number of the last column found by the macro MsgBox myLastColumn End Sub
Effects of Executing Macro Example to Find the Last Column in the Used Range
The following image illustrates the effects of using the macro example. As expected, Excel returns the number (6) of the last row in the active sheet’s used range. Excel considers formatting (including conditional formatting) when keeping track of a worksheet’s used range.
#17: Find the Last Column by Searching
VBA Code to Find the Last Column by Searching
To find the last column by searching with VBA, use a macro with the following statement structure:
If Application.CountA(Range) = 0 Then LastColumn = 0 Else LastColumn = Range.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End If
Process to Find the Last Column by Searching
To find the last column by searching with VBA, follow these steps:
- Identify the cell range whose last column you want to find (Range).
- Test if Range is empty (If Application.CountA(Range) = 0).
- If Range is empty (Then), handle this situation by, for example, assigning the value of 0 to the variable that will hold the number of the last column (LastColumn = 0).
- If Range isn’t empty (Else), search for the last cell in Range containing any character sequence (Range.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)).
- Obtain the column number of that last cell containing any character sequence (Column).
- Assign the number of the last column to the appropriate variable (LastColumn = …).
VBA Statement Explanation
Lines #1, #3 and #5: If Application.CountA(Range) = 0 Then | Else | End If
Item: If … Then | Else | End If
The If… Then… Else statement conditionally executes a group of statements (line #2 or line #4), depending on the value of an expression (Application.CountA(Range) = 0).
Item: Application.CountA(Range) = 0
Condition of the If… Then… Else statement, which evaluates to True or False as follows:
- True if all cells in Range are empty. For these purposes:
- Range is a Range object representing the cell range whose last column you want to find. You can usually work with, among others, the Worksheet.Range or Worksheet.Cells properties to refer to this Range object.
- The WorksheetFunction.CountA method (Application.CountA(Range)) counts the number of cells within Range that are not empty.
- False if at least 1 cell in Range isn’t empty.
In other words, this condition tests whether Range is empty (Application.CountA(Range) = 0) or not.
Line #2: LastColumn = 0
Statement that is executed if the condition tested by the If… Then… Else statement (Application.CountA(Range) = 0) returns True.
LastColumn is a variable of the Long data type to which you assign the number of the last column found by the macro.
If Range is empty (Application.CountA(Range) = 0), use the assignment operator (=) to assign an appropriate value (LastColumn = 0 assigns the value of 0) to LastColumn. In other words, use this statement (or set of statements) to handle the cases where Range is empty.
Line #4: LastColumn = Range.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Item: LastColumn
Variable of the Long data type to which you assign the number of the last column found by the macro (Range.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column).
Item: =
The assignment operator (=) assigns the number of the last column found by the macro (Range.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column) to LastColumn.
Item: Range
Range object representing the cell range whose last column you want to find.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)
The Range.Find method:
- Finds specific information in a cell range (Range); and
- Returns a Range object representing the first cell where the information is found.
When identifying the last column by searching, set the parameters of the Range.Find method as follows:
- What, which represents the data to search for, to “*” (What:=”*”). The asterisk (*) acts as a wildcard and results in Range.Find searching for any character sequence.
- LookIn, which specifies the type of data to search, to the xlFormulas built-in constant (or -4123) which refers to formulas (LookIn:=xlFormulas).
- LookAt, which specifies whether the match is made against the whole or any part of the search text, to the xlPart built-in constant (or 2) which matches against any part of the search text (LookAt:=xlPart).
- SearchOrder, which specifies the order in which to search the cell range, to the xlByColumns built-in constant (or 2) which searches across a column and then moves to the next column (SearchOrder:=xlByColumns).
- SearchDirection, which specifies the search direction, to the xlPrevious built-in constant (or 2) which searches for the previous match in the cell range (SearchDirection:=xlPrevious).
The settings for LookIn, LookAt, SearchOrder and MatchByte (used only if you have selected or installed double-byte language support) are saved every time you work with the Range.Find method. Therefore, if you don’t specify values for these parameters when searching for the last column, the saved values are used. Setting these parameters changes the settings in the Find dialog box and, vice-versa, changing the settings in the Find dialog box changes these parameters. Therefore, to reduce the risk of errors, set these arguments explicitly when searching for the last column.
Item: Column
The Range.Column property returns the number of the first column of the first area in the source range.
When identifying the last column by searching, the source range is the Range object returned by the Range.Find method (Range.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)). This Range object represents the last cell (furthest to the right) in the cell range you work with (Range). Therefore, the Range.Column property returns the number of that last column.
Macro Example to Find the Last Column by Searching
The following macro (User-Defined Function) example finds the last column in the cell range passed as argument (myRange) by searching. If myRange is empty (Application.CountA(myRange) = 0), the User-Defined Function returns the number 0 (lastColumnRangeFind = 0).
Function lastColumnRangeFind(myRange As Range) As Long 'Source: https://powerspreadsheets.com/ 'finds the last column in myRange by searching for the last cell with any character sequence. If myRange is empty, assigns the 0 as the number of the last row 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'test if myRange is empty If Application.CountA(myRange) = 0 Then 'if myRange is empty, assign 0 to lastColumnRangeFind lastColumnRangeFind = 0 Else 'if myRange isn't empty, find the last cell with any character sequence (What:="*") by: '(1) Searching for the previous match (SearchDirection:=xlPrevious); '(2) Across columns (SearchOrder:=xlByColumns) lastColumnRangeFind = myRange.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column End If End Function
Effects of Executing Macro Example to Find the Last Column by Searching
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (5) of the last column in the cell range passed as argument (A5 to F25) by searching.
#18: Find the Last Column in the Current Region
VBA Code to Find the Last Column in the Current Region
To find the last column in the current region with VBA, use a macro with the following statement structure:
With Cell.CurrentRegion LastColumn = .Columns(.Columns.Count).Column End With
Process to Find the Last Column in the Current Region
To find the last column in the current region with VBA, follow these steps:
- Identify the current region whose last column you want to find (With Cell.CurrentRegion | End With).
- Identify the last column in the current region (.Columns(.Columns.Count)).
- Obtain the number of that last column in the current region (Column).
- Assign the number of the last column to a variable (LastColumn = …).
VBA Statement Explanation
Lines #1 and #3: With Cell.CurrentRegion | End With
Item: With … | End With
The With… End With statement executes a series of statements (line #2) on a single object (Cell.CurrentRegion).
Item: Cell
Range object representing a cell in the current region whose last column you want to find.
You can usually work with, among others, the following properties to refer to this Range object:
- Worksheet.Range.
- Worksheet.Cells.
Item: CurrentRegion
The Range.CurrentRegion property returns a Range object representing the current region. The current region is a cell range bounded by a combination of:
- Blank rows; and
- Blank columns.
The Range.CurrentRegion property (basically) expands from Cell to include the entire current region.
Line #2: LastColumn = .Columns(.Columns.Count).Column
Item: LastColumn
Variable of the Long data type to which you assign the number of the last column found by the macro (.Columns(.Columns.Count).Column).
Item: =
The assignment operator (=) assigns the number of the last column found by the macro (.Columns(.Columns.Count).Column) to LastColumn.
Item: .Columns(.Columns.Count)
The Range.Columns property returns a Range object representing the columns in the source range (Cell.CurrentRegion).
The Range.Count property returns the number of objects in a collection. When searching for the last column in the current region, the Range.Count property returns the number of columns in the source range (.Columns).
Therefore:
- .Columns returns a Range object representing all columns in Cell.CurrentRegion.
- .Columns.Count returns the number of columns in Cell.CurrentRegion.
.Columns.Count is used as an index number of the Range.Columns property (.Columns(.Columns.Count)). In other words, .Columns(.Columns.Count) refers to the column (within Cell.CurrentRegion) whose index number is equal to the number of columns in Cell.CurrentRegion (.Columns.Count). This is the last column in Cell.CurrentRegion.
Item: Column
The Range.Column property returns the number of the first column of the first area in the source range.
When searching for the last column in the current region, the source range is that last column of that current region (.Columns(.Columns.Count)). Therefore, the Range.Column property returns the number of that last column.
Macro Example to Find the Last Column in the Current Region
The following macro example finds the last column in the current region (myCell.CurrentRegion) containing cell A6 in the active worksheet (ActiveSheet.Range(“A6”)).
Sub lastColumnInCurrentRegion() 'Source: https://powerspreadsheets.com/ 'finds the last column in the current region containing cell A6 in the active worksheet 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'declare object variable to represent source range Dim myCell As Range 'declare variable to hold value of last column Dim myLastColumn As Long 'identify source range Set myCell = ActiveSheet.Range("A6") 'identify the current region containing myCell With myCell.CurrentRegion 'find the last column in the current region containing myCell myLastColumn = .Columns(.Columns.Count).Column End With 'display the number of the last column found by the macro MsgBox myLastColumn End Sub
Effects of Executing Macro Example to Find the Last Column in the Current Region
The following image illustrates the effects of using the macro example. As expected, Excel returns the number (5) of the last column in the current region containing cell A6.
#19: Find the Last Column in an Excel Table
VBA Code to Find the Last Column in an Excel Table
To find the last column in an Excel Table with VBA, use a macro with the following statement structure:
With ExcelTable.Range LastColumn = .Columns(.Columns.Count).Column End With
Process to Find the Last Column in an Excel Table
To find the last column in an Excel Table with VBA, follow these steps:
- Identify the Excel Table whose last column you want to find (With ExcelTable.Range | End With).
- Identify the last column in the Excel Table (.Columns(.Columns.Count)).
- Obtain the number of that last column in the Excel Table (Column).
- Assign the number of the last column to a variable (LastColumn = …).
VBA Statement Explanation
Lines #1 and #3: With ExcelTable.Range | End With
Item: With … | End With
The With… End With statement executes a series of statements (line #2) on a single object (ExcelTable.Range).
Item: ExcelTable
ListObject object representing the Excel Table whose last column you want to find.
You can usually work with the Worksheet.ListObjects property to refer to this ListObject object.
Item: Range
The ListObject.Range property returns a Range object representing the cell range to which ExcelTable applies.
Line #2: LastColumn = .Columns(.Columns.Count).Column
Item: LastColumn
Variable of the Long data type to which you assign the number of the last column found by the macro (.Columns(.Columns.Count).Column).
Item: =
The assignment operator (=) assigns the number of the last column found by the macro (.Columns(.Columns.Count).Column) to LastColumn.
Item: .Columns(.Columns.Count)
The Range.Columns property returns a Range object representing the columns in the source range (ExcelTable.Range).
The Range.Count property returns the number of objects in a collection. When searching for the last column in an Excel Table, the Range.Count property returns the number of columns in the source range (.Columns).
Therefore:
- .Columns returns a Range object representing all columns in ExcelTable.Range.
- .Columns.Count returns the number of columns in ExcelTable.Range.
.Columns.Count is used as an index number of the Range.Columns property (.Columns(.Columns.Count)). In other words, .Columns(.Columns.Count) refers to the column (within ExcelTable.Range) whose index number is equal to the number of columns in ExcelTable.Range (.Columns.Count). This is the last column in ExcelTable.Range.
Item: Column
The Range.Column property returns the number of the first column of the first area in the source range.
When searching for the last column in an Excel Table, the source range is that last column of the Excel Table (.Columns(.Columns.Count)). Therefore, the Range.Column property returns the number of that last column.
Macro Example to Find the Last Column in an Excel Table
The following macro (User-Defined Function) example finds the last column in an Excel Table (ListObjects(myTableIndex).Range):
- Located in the same worksheet as that where the User-Defined Function is used in a worksheet formula (Application.Caller.Parent); and
- Whose index number is passed as argument of the User-Defined Function (myTableIndex).
Function lastColumnInTable(myTableIndex As Long) As Long 'Source: https://powerspreadsheets.com/ 'finds the last column in an Excel Table (in the same worksheet as that where the User-Defined Function is used and whose index number is myTableIndex) 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'identify the cell range containing the Excel Table located in the same worksheet as that where the User-Defined Function is used and whose index number is myTableIndex With Application.Caller.Parent.ListObjects(myTableIndex).Range 'find the last column in the Excel Table lastColumnInTable = .Columns(.Columns.Count).Column End With End Function
Effects of Executing Macro Example to Find the Last Column in an Excel Table
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (5) of the last column in the Excel Table whose index number (1) is passed as argument.
#20: Find the Last Column in a Named Cell Range
VBA Code to Find the Last Column in a Named Cell Range
To find the last column in a named cell range with VBA, use a macro with the following statement structure:
With NamedRange LastColumn = .Columns(.Columns.Count).Column End With
Process to Find the Last Column in a Named Cell Range
To find the last column in a named cell range with VBA, follow these steps:
- Identify the named cell range whose last column you want to find (With NamedRange | End With).
- Identify the last column in the named cell range (.Columns(.Columns.Count)).
- Obtain the number of that last column in the named cell range (Column).
- Assign the number of the last column to a variable (LastColumn = …).
VBA Statement Explanation
Lines #1 and #3: With NamedRange | End With
The With… End With statement executes a series of statements (line #2) on a single object (NamedRange).
NamedRange is a Range object representing the named cell range whose last column you want to find. You can usually work with the Worksheet.Range property to refer to this Range object.
Line #2: LastColumn = .Columns(.Columns.Count).Column
Item: LastColumn
Variable of the Long data type to which you assign the number of the last column found by the macro (.Columns(.Columns.Count).Column).
Item: =
The assignment operator (=) assigns the number of the last column found by the macro (.Columns(.Columns.Count).Column) to LastColumn.
Item: .Columns(.Columns.Count)
The Range.Columns property returns a Range object representing the columns in the source range (NamedRange).
The Range.Count property returns the number of objects in a collection. When searching for the last column in a named cell range, the Range.Count property returns the number of columns in the source range (.Columns).
Therefore:
- .Columns returns a Range object representing all columns in NamedRange.
- .Columns.Count returns the number of columns in NamedRange.
.Columns.Count is used as an index number of the Range.Columns property (.Columns(.Columns.Count)). In other words, .Columns(.Columns.Count) refers to the column (within NamedRange) whose index number is equal to the number of columns in NamedRange (.Columns.Count). This is the last column in NamedRange.
Item: Column
The Range.Column property returns the number of the first column of the first area in the source range.
When searching for the last column in a named cell range, the source range is the last column of that named cell range (.Columns(.Columns.Count)). Therefore, the Range.Column property returns the number of that last column.
Macro Example to Find the Last Column in a Named Cell Range
The following macro (User-Defined Function) example finds the last column in a named cell range (Range(myRangeName)):
- Located in the same worksheet as that where the User-Defined Function is used in a worksheet formula (Application.Caller.Parent); and
- Whose name is passed as argument of the User-Defined Function (myRangeName).
Function lastColumnInNamedRange(myRangeName As String) As Long 'Source: https://powerspreadsheets.com/ 'finds the last column in a named cell range (in the same worksheet as that where the User-Defined Function is used and whose name is myRangeName) 'For further information: https://powerspreadsheets.com/vba-last-row-column/ 'identify the named cell range whose name is myRangeName With Application.Caller.Parent.Range(myRangeName) 'find the last column in myRangeName lastColumnInNamedRange = .Columns(.Columns.Count).Column End With End Function
Effects of Executing Macro Example to Find the Last Column in a Named Cell Range
The following image illustrates the effects of using the macro (User-Defined Function) example. As expected, Excel returns the number (5) of the last column in the named cell range passed as argument (namedRangeColumn).
Workbook Example Used in this VBA Last Row and Last Column Tutorial
You can get immediate free access to the example workbook that accompanies this VBA Last and Last Column Tutorial by subscribing to the Power Spreadsheets Newsletter.
To find the last row, column, or cell you can use the range’s “End” property. The end property allows you to navigate to the end of the data range (to the last cell that is not empty). With this, there are constants that you can use to decide in which direction you want to navigate (top, bottom, left, or right).
- Define the cell or the range from where you want to navigate to the last row.
- After that, enter a dot to get the list of properties and methods.
- Select or type “End” and enter a starting parenthese.
- Use the argument that you want to use.
- Further, use the address property to get the address of the cell.
MsgBox Range("A1").End(xlDown).Address
When you run the above code, it shows you a message box with the row number of the last non-empty cell.
Find the Last Column using VBA
Now, let’s say you want to find the last column. In that case, instead of using “xlDown” constant, you need to use the “xlRight”, and if you want to select that cell instead of having the address then you can use the “select” method. Consider the following method.
Range("A1").End(xlToRight).Select
Find the Last Cell
By using the same method, you can also get the last cell which is a non-empty cell. To write this code, you need to know the last row and column.
Sub vba_last_row()
Dim lRow As Long
Dim lColumn As Long
lRow = Range("A1").End(xlDown).Row
lColumn = Range("A1").End(xlToRight).Column
Cells(lRow, lColumn).Select
End Sub
To understand the above code, we need to split it into three parts.
- In the FIRST part, you have declared two variables to store the row and the column number.
- In the SECOND part, you have used “End” with the “xlDown” and then the Row property to get the row number of the last, and in the same way, you have used the “End” with the “xlToRight” and then the “Column” property to get the column number of the last column.
- In the THIRD part, by using the last column number and last row number refer to the last cell and select it.
Note: If you want to select a cell in the different worksheets using the last row and last column method, you need to have that worksheet activated first.
Last Row, Column, and Cell using the Find Method
You can also use the find method with the range object to get the worksheet’s last row, column, and cell. To know the row number, here is the code:
Sub vba_last_row()
Dim iRow As Long
iRow = Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
MsgBox iRow
End Sub
For column number:
Sub vba_last_row()
Dim iColumn As Long
iColumn = Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
MsgBox iColumn
End Sub
To get the cell address of the last cell.
Sub vba_last_row()
Dim iColumn As Long
Dim iRow As Long
iColumn = Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
iRow = Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Cells(iRow, iColumn).Address
End Sub
More Tutorials
- Count Rows using VBA in Excel
- Excel VBA Font (Color, Size, Type, and Bold)
- Excel VBA Hide and Unhide a Column or a Row
- Excel VBA Range – Working with Range and Cells in VBA
- Apply Borders on a Cell using VBA in Excel
- Insert a Row using VBA in Excel
- Merge Cells in Excel using a VBA Code
- Select a Range/Cell using VBA in Excel
- SELECT ALL the Cells in a Worksheet using a VBA Code
- ActiveCell in VBA in Excel
- Special Cells Method in VBA in Excel
- UsedRange Property in VBA in Excel
- VBA AutoFit (Rows, Column, or the Entire Worksheet)
- VBA ClearContents (from a Cell, Range, or Entire Worksheet)
- VBA Copy Range to Another Sheet + Workbook
- VBA Enter Value in a Cell (Set, Get and Change)
- VBA Insert Column (Single and Multiple)
- VBA Named Range | (Static + from Selection + Dynamic)
- VBA Range Offset
- VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
- VBA Wrap Text (Cell, Range, and Entire Worksheet)
- VBA Check IF a Cell is Empty + Multiple Cells
⇠ Back to What is VBA in Excel
Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes
NOTE: I intend to make this a «one stop post» where you can use the Correct
way to find the last row. This will also cover the best practices to follow when finding the last row. And hence I will keep on updating it whenever I come across a new scenario/information.
Unreliable ways of finding the last row
Some of the most common ways of finding last row which are highly unreliable and hence should never be used.
- UsedRange
- xlDown
- CountA
UsedRange
should NEVER be used to find the last cell which has data. It is highly unreliable. Try this experiment.
Type something in cell A5
. Now when you calculate the last row with any of the methods given below, it will give you 5. Now color the cell A10
red. If you now use the any of the below code, you will still get 5. If you use Usedrange.Rows.Count
what do you get? It won’t be 5.
Here is a scenario to show how UsedRange
works.
xlDown
is equally unreliable.
Consider this code
lastrow = Range("A1").End(xlDown).Row
What would happen if there was only one cell (A1
) which had data? You will end up reaching the last row in the worksheet! It’s like selecting cell A1
and then pressing End key and then pressing Down Arrow key. This will also give you unreliable results if there are blank cells in a range.
CountA
is also unreliable because it will give you incorrect result if there are blank cells in between.
And hence one should avoid the use of UsedRange
, xlDown
and CountA
to find the last cell.
Find Last Row in a Column
To find the last Row in Col E use this
With Sheets("Sheet1")
LastRow = .Range("E" & .Rows.Count).End(xlUp).Row
End With
If you notice that we have a .
before Rows.Count
. We often chose to ignore that. See THIS question on the possible error that you may get. I always advise using .
before Rows.Count
and Columns.Count
. That question is a classic scenario where the code will fail because the Rows.Count
returns 65536
for Excel 2003 and earlier and 1048576
for Excel 2007 and later. Similarly Columns.Count
returns 256
and 16384
, respectively.
The above fact that Excel 2007+ has 1048576
rows also emphasizes on the fact that we should always declare the variable which will hold the row value as Long
instead of Integer
else you will get an Overflow
error.
Note that this approach will skip any hidden rows. Looking back at my screenshot above for column A, if row 8 were hidden, this approach would return 5
instead of 8
.
Find Last Row in a Sheet
To find the Effective
last row in the sheet, use this. Notice the use of Application.WorksheetFunction.CountA(.Cells)
. This is required because if there are no cells with data in the worksheet then .Find
will give you Run Time Error 91: Object Variable or With block variable not set
With Sheets("Sheet1")
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastrow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If
End With
Find Last Row in a Table (ListObject)
The same principles apply, for example to get the last row in the third column of a table:
Sub FindLastRowInExcelTableColAandB()
Dim lastRow As Long
Dim ws As Worksheet, tbl as ListObject
Set ws = Sheets("Sheet1") 'Modify as needed
'Assuming the name of the table is "Table1", modify as needed
Set tbl = ws.ListObjects("Table1")
With tbl.ListColumns(3).Range
lastrow = .Find(What:="*", _
After:=.Cells(1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End With
End Sub
VBA END Function
End Statement is almost used in every other programming language, so VBA is also not different from it. Every code has a start and has an end for it. How do we end any specific function or code is different in programming languages. In VBA we close our code by using END Statement. But apart from this end statement, we have another end function in VBA which is used to refer to the cells of a worksheet which we will talk about detail in this article.
As I have told above we will be discussing another property of END in VBA which is used to refer to the end of the cells. There are many separate properties for this END function. For example, end to the right or end the left or end to the bottom. To make this more clear look at below the image.
In Excel worksheet how do we move from cell A1 which points A to cell E1 which is point B? We press CTRL + right arrow. Similarly to move from point B to point C we press CTRL + Down Arrow and from point C to point D we press CTRL + Left arrow. Similarly for point D to point A we press CTRL + Up arrow.
This is also known as to refer to the next cell which has some value in it. This process skips the blank cells and moves to the end of the reference. In VBA we do not press CTRL + Right Arrow to move from point A to point B. We use properties of END to do this. And this is what we will learn in this article. How can we move from Point A to End to the right which is point B and select the cell range and do the same for others.
How to Use VBA End Function in Excel?
We will learn how to use a VBA END Function with example in excel.
You can download this VBA END Excel Template here – VBA END Excel Template
Let us learn to do so by a few examples.
Example #1 – VBA END
In the first example let us select cell E1 using the end property in VBA.
Step 1: From the Insert tab insert a new module. Remember we will work in the same module for the entire article. We can see the module in the project window, Open the module as shown below.
Step 2: Start the Sub procedure in the window.
Code:
Sub sample() End Sub
Step 3: Now we know that we have to move from cell A1 to cell E1 so type the following code.
Code:
Sub sample() Range ("A1") End Sub
Step 4: Now put a dot after the parenthesis and write end as shown below.
Code:
Sub sample() Range("A1").End End Sub
Step 5: Press Enter and open a parenthesis we will see some more options in the end statement as follows,
Code:
Sub sample() Range("A1").End( End Sub
Step 6: Select XltoRight as we have to move right to select cell E1.
Code:
Sub sample() Range("A1").End (xlToRight) End Sub
Step 7: Now to select the range, put a dot after the closing parenthesis and write select as shown below.
Code:
Sub sample() Range("A1").End(xlToRight).Select End Sub
Step 8: Now let us execute the code written above and see the result in sheet 1 as follows.
From Point A which is cell A1 we moved to the end of the data in the right which is cell E1.
Example #2 – VBA END
Similar to the above example where we moved right from the cell A1 we can move left too. Let us select cell A5 which is point C from Point D.
Step 1: In the same module, declare another subprocedure for another demonstration.
Code:
Sub Sample1() End Sub
Step 2: Now let us move from cell E5 to cell A5, so first refer to cell E5 as follows.
Code:
Sub Sample1() Range ("E5") End Sub
Step 3: Now let us move to the left of the cell E5 using the end statement.
Code:
Sub Sample1() Range("E5").End (xlToLeft) End Sub
Step 4: Now to select cell A5 put a dot after the parenthesis and write select.
Code:
Sub Sample1() Range("E5").End(xlToLeft).Select End Sub
Step 5: Now execute this code above and see the result in sheet 1 as follows.
From point C we moved to point D using the end statement.
Example #3 – VBA END
Now let use the downwards end statement which means we will select cell A5 from cell A1.
Step 1: In the same module, declare another subprocedure for another demonstration.
Code:
Sub Sample2() End Sub
Step 2: Now let us move from cell A5 to cell A1, so first refer to cell A1 as follows.
Code:
Sub Sample2() Range ("A1") End Sub
Step 3: Now let us move to the down of the cell A1 using the end statement.
Code:
Sub Sample2() Range("A1").End (xlDown) End Sub
Step 4: Now to select cell A5 put a dot after the parenthesis and write select.
Code:
Sub Sample2() Range("A1").End(xlDown).Select End Sub
Step 5: Now execute this code above and see the result in sheet 1 as follows.
We have moved from Point A to point D using the down property of the end statement.
Example #4 – VBA END
Now let us select the total range from Point A to Point B to Point C and to Point D using the end statement.
Step 1: In the same module, declare another subprocedure for another demonstration.
Code:
Sub FinalSample() End Sub
Step 2: Now let us select from cell A1 to cell E5, so first refer to cell A1 as follows.
Code:
Sub FinalSample() Range("A1" End Sub
Step 3: Now let us move down of the cell A1 using the end statement.
Code:
Sub FinalSample() Range("A1", Range("A1").End(xlDown) End Sub
Step 4: Now we need to move to the right of the cell A1 by using the following end statement as follows.
Code:
Sub FinalSample() Range("A1", Range("A1").End(xlDown).End(xlToRight)) End Sub
Step 5: Select the cell range using the select statement.
Code:
Sub FinalSample() Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select End Sub
Step 6: Let us run the above code and see the final result in sheet 1 as follows.
Things to Remember
- The method to use END in VBA Excel to refer cells is very easy. We refer to a range first
- Range( Cell ) and then we use End property to select or go to the last used cell in the left-right or down of the reference cell
- Range (Cell).End(XltoRight) to got to the right of the cell.
- First things which we need to remember is END property is different to the ending of a procedure or a function in VBA.
- We can use a single property to refer to a cell i.e. to right or left of it or we can select the whole range together.
- In a worksheet, we use the same reference using the CTRL button but in VBA we use the END statement.
Recommended Articles
This is a guide to VBA END. Here we discuss how to use Excel VBA END Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA InStr
- VBA Integer
- VBA ISNULL
- VBA Transpose