Хитрости »
1 Май 2011 403775 просмотров
Очень часто при внесении данных на лист Excel возникает вопрос определения последней заполненной или первой пустой ячейки. Чтобы впоследствии с этой первой пустой ячейки начать заносить данные. В этой теме я опишу несколько способов определения последней заполненной ячейки.
В качестве переменной, которой мы будем присваивать номер последней заполненной строки, у нас во всех примерах будет lLastRow. Объявлять мы её будем как Long. Для экономии памяти можно было бы использовать и тип Integer, но т.к. строк на листе может быть больше 32767(это максимальное допустимое значение переменных типа Integer) нам понадобиться именно Long, во избежание ошибки. Подробнее про типы переменных можно прочитать в статье Что такое переменная и как правильно её объявить
Одинаковые переменные для всех примеров
Во всех примерах ниже мы будем запоминать номер последней строки или столбца в одни и те же переменные:
Dim lLastRow As Long 'а для lLastCol можно было бы применить и тип Integer, 'т.к. столбцов в Excel пока меньше 32767, но для однообразности назначим тоже Long Dim lLastCol As Long
Способ 1:
Определение
последней заполненной строки
через свойство End
lLastRow = Cells(Rows.Count,1).End(xlUp).Row 'или lLastRow = Cells(Rows.Count, "A").End(xlUp).Row
1 или «A» — это номер или имя столбца, последнюю заполненную ячейку в котором мы определяем. По сути обе приведенные строки дадут абсолютно одинаковый результат. Просто иногда удобнее указать номер столбца, а иногда его имя. Поэтому использовать можно любой из приведенных вариантов, в зависимости от ситуации.
Определение последнего столбца через свойство End
lLastCol = Cells(1, Columns.Count).End(xlToLeft).Column
1 — это номер строки, последнюю заполненную ячейку в которой мы определяем.
Данный метод определения последней строки/столбца самый распространенный. Используя его мы можем определить последнюю ячейку только в одном конкретном столбце(или строке). В большинстве случаев этого более чем достаточно.
Метод основан именно на принципе работы свойства End. На примере поиска последней строки опишу принцип так, как бы мы это делали руками через выделение ячеек на листе:
- выделили самую последнюю ячейку столбца А на листе(для Excel 2007 и выше это А1048576, а для Excel 2003 — А65536)
- и выполнили переход вверх комбинацией клавиш Ctrl+стрелка вверх. Данная комбинация заставляет Excel двигаться вверх(если точнее, то в направлении стрелки, нажатой вместе с Ctrl) до тех пор, пока не встретиться первая ячейка с формулой или значением. А в случае, если сочетание было вызвано из уже заполненных ячеек — то до первой пустой. И как только Excel доходит до этой ячейки — он её выделяет
- А через свойство .Row мы просто получаем номер строки этой выделенной ячейки
Нюансы:
- даже если в ячейке нет видимого значения, но есть формула — End посчитает ячейку не пустой. С одной стороны вполне справедливо. Но иногда нам надо определить именно «визуально» заполненные ячейки. Поиск ячеек при подобных условиях будет описан ниже(Способ 4: Определение последней ячейки через метод Find)
- если на листе заполнены все строки в просматриваемом столбце(или будут заполнены несколько последних ячеек столбца или даже только одна последняя) — то результат может быть неверный(ну или не совсем такой, какой ожидали)
- Данный способ игнорирует строки, скрытые фильтром, группировкой или командой Скрыть (Hide). Т.е. если последняя строка таблицы будет скрыта, то данный метод вернет номер последней видимой заполненной строки, а не последней реально заполненной.
Ну а если надо получить первую пустую ячейку на листе(а не первую заполненную) — придется вспомнить математику. Т.к. последнюю заполненную мы определили, то первая пустая — следующая за ней. Т.е. к результату необходимо прибавить 1. Это хоть и очевидно, но на всякий случай все же лучше об этом напомнить.
Способ 2:
Определение
последней заполненной строки
через SpecialCells
lLastRow = Cells.SpecialCells(xlLastCell).Row
Определение последнего столбца через SpecialCells
lLastCol = Cells.SpecialCells(xlLastCell).Column
Данный метод не требует указания номера столбца и возвращает последнюю ячейку(Row — строку, Column — столбец).
Если хотите получить номер первой пустой строки или столбца на листе — к результату необходимо прибавить 1.
Нюансы:
- Используя данный способ следует помнить, что не всегда можно получить реальную последнюю заполненную ячейку, т.е. именно ячейку со значением. Метод SpecialCells определяет самую «дальнюю» ячейку на листе, используя при этом механизм «запоминания» тех ячеек, в которых мы работали в данном листе. Т.е. если мы занесем в ячейку AZ90345 значение и сразу удалим его — lLastRow, полученная через SpecialCells будет равна значению именно этой ячейки, из которой вы только что удалили значения(т.е. 90345). Другими словами требует обязательного обновления данных, а этого можно добиться только сохранив файла, а временами даже только закрыв файл и открыв его снова. Так же, если какая-либо ячейка содержит форматирование(например, заливку), но не содержит никаких значений, то метод SpecialCells посчитает её используемой и будет учитывать как заполненную.
Этот недостаток можно попробовать обойти, вызвав перед определением последней ячейки вот такую строку кода:With ActiveSheet.UsedRange: End With
Это должно переопределить границы рабочего диапазона и тогда определение последней строки/столбца сработает как ожидается, даже если до этого в ячейке содержались данные, которые впоследствии были удалены.
Выглядеть в единой процедуре это будет так:Sub GetLastCell() Dim lLastRow As Long 'переопределяем рабочий диапазон листа With ActiveSheet.UsedRange: End With 'ищем последнюю заполненную ячейку на листе lLastRow = Cells.SpecialCells(xlLastCell).Row End Sub
- даже если в ячейке нет видимого значения, но есть формула — SpecialCells посчитает ячейку не пустой
- Данный метод определения последней ячейки не будет работать на защищенном листе(Рецензирование(Review) —Защитить лист(Protect Sheet)).
- Данный метод не будет работать при использовании внутри UDF. Точнее будет работать не так, как ожидается. Подробнее про некоторые «баги» работы встроенных методов внутри UDF(функций пользователя) я описывал в этой статье: Глюк работы в UDF методов SpecialCells и FindNext
Сам же я этот метод обычно использую для определения последней ячейки в только что созданном файле, в котором только добавляю строки кодом и в котором не может быть описанных выше нюансов.
Способ 3:
Определение последней строки через UsedRange
lLastRow = ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count - 1
Определение последнего столбца через UsedRange
lLastCol = ActiveSheet.UsedRange.Column + ActiveSheet.UsedRange.Columns.Count - 1
НЕМНОГО ПОЯСНЕНИЙ:
- ActiveSheet.UsedRange.Row — этой строкой мы определяем первую ячейку, с которой начинаются данные на листе. Важно понимать для чего это — если у вас первые строк 5 не заполнены ничем(т.е. самые первые данные заносились начиная с 6-ой строки листа), то ActiveSheet.UsedRange.Row вернет именно 6(т.е. номер первой строки с данными). Если же все строки заполнены — то вернет 1.
- ActiveSheet.UsedRange.Rows.Count — определяем кол-во строк, входящих в весь диапазон данных на листе. При этом неважно, есть ли данные в ячейках или нет — достаточно было поработать в этих ячейках и удалить значения или просто изменить цвет заливки.
В итоге получается: первая строка данных + кол-во строк с данными — 1. Зачем вычитать единицу? Попробуем посчитать вместе: первая строка: 6. Всего строк: 3. 6 + 3 = 9. Вроде все верно. А теперь выделим на листе три ячейки, начиная с 6-ой. Выделение завершилось на 8-ой строке. Потому что в 6-ой строке уже есть данные. Поэтому и надо вычесть 1, чтобы учесть этот момент. Думаю, не надо пояснять, что если надо получить первую пустую ячейку — можно 1 не вычитать - То же самое и с ActiveSheet.UsedRange.Column, только уже не для строк, а для столбцов.
Нюансы:
- Обладает некоторыми недостатками предыдущего метода. Определяет самую «дальнюю» ячейку на листе, используя при этом механизм «запоминания» тех ячеек, в которых мы работали в данном листе. Следовательно попробовать обойти этот момент можно точно так же: перед определением последней строки/столбца записать строку: With ActiveSheet.UsedRange: End With
Это должно переопределить границы рабочего диапазона и тогда определение последней строки/столбца сработает как ожидается, даже если до этого в ячейке содержались данные, которые впоследствии были удалены. - даже если в ячейке нет видимого значения, но есть формула — UsedRange посчитает ячейку не пустой
Однако метод через UsedRange.Row работает прекрасно и при установленной на лист защите и внутри UDF, что делает его более предпочтительным, чем метод через SpecialCells при равных условиях.
Способ 4:
Определение последней строки и столбца, а так же адрес ячейки методом Find
Sub GetLastCell_Find() Dim rF As Range Dim lLastRow As Long, lLastCol As Long 'ищем последнюю ячейку на листе, в которой хранится хоть какое-то значение Set rF = ActiveSheet.UsedRange.Find(What:="*", LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlPrevious, MatchCase:=False, MatchByte:=False) If Not rF Is Nothing Then lLastRow = rF.Row 'последняя заполненная строка lLastCol = rF.Column 'последний заполненный столбец MsgBox rF.Address 'показываем сообщение с адресом последней ячейки Else 'если ничего не нашлось - значит лист пустой 'и можно назначить в качестве последних первую строку и столбец lLastRow = 1 lLastCol = 1 MsgBox "A1" 'показываем сообщение с адресом ячейки А1 End If End Sub
Этот метод, пожалуй, самый оптимальный в случае, если надо определить последнюю строку/столбец на листе без учета форматов и формул — только по отображаемому значению в ячейке. Например, если на листе большая таблица и последние строки заполнены формулами, возвращающими при определенных условиях пустую ячейку(=ЕСЛИ(A1>0;1;»»)), предыдущие варианты вернут строку/столбец ячейки с последней ячейкой, в которой формула. В то время как данный метод вернет адрес ячейки только в случае, если в ячейке реально отображается какое-то значение. Такой подход часто используется для того, чтобы определить границы данных для последующего анализа заполненных данных, чтобы не захватывать пустые ячейки с формулами и не тратить время на их проверку.
Здесь следует обратить внимание на параметры метода Find. В данном случае мы специально указываем искать по значениям, а не по формулам:
Set rF = ActiveSheet.UsedRange.Find(What:=»*», LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlPrevious, MatchCase:=False, MatchByte:=False)
Нюансы:
- Метод Find, вызванный с листа или другим кодом, имеет свойство запоминать все параметры последнего поиска, а если поиск еще не вызывался — то применяются параметры по умолчанию. А по умолчанию поиск идет всегда по формулам. Поэтому я настоятельно рекомендую указывать принудительно все необходимые параметры, как в примере.
- Метод Find не будет учитывать в просмотре скрытые строки и столбцы. Это следует учитывать при его применении.
Пара небольших практических кодов
Коды ниже могут помочь понять, как использовать приведенные выше строки кода по поиску последней ячейки/строки:
Sub GetLastCell() Dim lLastRow As Long Dim lLastCol As Long 'определили последнюю заполненную ячейку с учетом формул в столбце А lLastRow = Cells(Rows.Count, 1).End(xlUp).Row MsgBox "Заполненные ячейки в столбце А: " & Range("A1:A" & lLastRow).Address 'определили последний заполненный столбец на листе(с учетом формул и форматирования) lLastCol = Cells.SpecialCells(xlLastCell).Column MsgBox "Заполненные ячейки в первой строке: " & Range(Cells(1, 1), Cells(1, lLastCol)).Address 'выводим сообщение с адресом последней ячейки на листе(с учетом формул и форматирования) MsgBox "Адрес последней ячейки диапазона на листе: " & Cells.SpecialCells(xlLastCell).Address End Sub
Выделяем диапазон ячеек в столбцах с А по С, определяя последнюю ячейку по столбцу A этого же листа:
Sub SelectToLastCell() Range("A1:C" & Cells(Rows.Count, 1).End(xlUp).Row).Select End Sub
Копируем ячейку B1 в первую пустую ячейку столбца A этого же листа:
Sub CopyToFstEmptyCell() Dim lLastRow As Long lLastRow = Cells(Rows.Count, 1).End(xlUp).Row 'определили последнюю заполненную ячейку Range("B1").Copy Cells(lLastRow+1, 1) 'скопировали В1 и вставили в следующую после определенной ячейки End Sub
А код ниже делает тоже самое, но одной строкой — применяется Offset и используется тот факт, что изначально методом End мы получаем именно ячейку, а не номер строки(номер строки мы получаем позже через свойство .Row):
Sub CopyToFstEmptyCell() Range("B1").Copy Destination:=Cells(Rows.Count, 1).End(xlUp).Offset(1) End Sub
Range(«B1»).Copy — копирует ячейку В1. Если для аргумента Destination указать другую ячейку, то в неё будет вставлена скопированная ячейка. Мы передаем в этот аргумент определенную методом End ячейку
Cells(Rows.Count, 1).End(xlUp) — возвращает последнюю заполненную ячейку в столбце А (не строку, а именно ячейку)
Offset(1) — смещает полученную ячейку на строку вниз
Используем инструмент автозаполнение(протягивание) столбца В, начиная с ячейки B2 и определяя последнюю ячейку для заполнения на основании столбца А
Sub AutoFill_B() Dim lLastRow As Long lLastRow = Cells(Rows.Count, 1).End(xlUp).Row Range("B2").AutoFill Destination:=Range("B2:B" & lLastRow) End Sub
На самом деле практических кодов может быть куда больше, т.к. определение последней заполненной или первой пустой ячейки является чуть ли не самой распространенной задачей при написании кодов в Excel.
Так же см.:
Как получить последнюю заполненную ячейку формулой?
Как определить первую заполненную ячейку на листе?
Что такое переменная и как правильно её объявить?
Статья помогла? Поделись ссылкой с друзьями!
Видеоуроки
Поиск по меткам
Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика
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
Dynamic VBA Code With Last Row/Column
Finding the Last Row or Last Column within your VBA code is key to ensuring your macro doesn’t break in the future.
Early on when I first began writing VBA macro code, I always needed to go back into the code and modify range references. I had created a bunch of macros to clean up and perform analysis on raw data exported from databases and the data never had the same amount of rows from one data pull to the next.
My coding skills dramatically changed the day I realized my VBA code could be dynamic and automatically determine the size of my raw data once executed. I soon came to realize the goal of coding a macro: to write it once and never touch it again.
Variability is also the greatest challenge for any VBA coder as you have to think of every possible change that could occur in the future. I have found writing VBA code that can automatically resize itself is one of the greatest things missing from most average macro user’s code.
In this article, I have compiled a list of the best methods you can use to accomplish finding the last row or column in your data range.
Prep Your Excel Data!
Keep in mind some of these methods may not give you the desired row or column number if you are not setting your spreadsheet up properly or using a well-formatted block of data.
What I mean by a “well-formatted block of data”, is a worksheet with data that starts in cell A1 and does not have any blank rows or columns in the middle of the data.
The below figure illustrates the difference.
An Example of a Poorly-Formatted Data Set
An Example of a Well-Formatted Data Set
In a data set starting in Row 4, you may need to add or subtract a numerical value depending on the method you use. If you are going to be coding for a data set that has blank rows or columns within it, always be sure to test out your code to make sure it is calculating properly.
Find the Last Cell In Spreadsheet With Data
Finding the last cell with a value in it is key to determining the last row or last column. There are a couple of different ways you can locate the last cell on your spreadsheet. Let’s take a look!
1. The Find Function Method (Best Method)
This line of VBA code will search all the cells on your sheet and return the row of the last cell with any sort of value stored in it. Because the Find function is set to search from the very bottom of the spreadsheet and upwards, this code can accommodate blank rows in your data.
Dim LastCell As Range
Set LastCell = ActiveSheet.Cells.Find(«*», SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
This method ignores empty cells with formatting still in them, which is ideal if you are truly wanting the find the last cell with data in it, not necessarily the last cell that had any modifications done to it.
2. SpecialCells Method
One of the best manual ways to do this is to utilize the Go To Special dialog box.
The Go To Special dialog box has a variety of actions that can be taken to select certain cells or objections on your spreadsheet. One of those options is to select the Last Cell on the active spreadsheet.
You can get to the Go To Special dialog box by using the keyboard shortcut Ctrl + G which will open the Go To dialog box. From there you can click the Special button and you’ll have arrived at the Go To Special dialog box.
In VBA, the select actions in the Go To Special dialog box are simply called SpecialCells. By calling the SpecialCells function in VBA, you gain the same actions, though they have slightly different names. The particular action you’ll want to call is named xlCellTypeLastCell.
The below VBA code stores the last cell found on the spreadsheet with a value in it to a range variable.
Dim LastCell As Range
Set LastCell = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell)
WARNING! This method could give you unintended results as this finds the last cell with any sort of data or formatting associated with it. This means it can return an empty cell that used to have data in it or simply has any formatting changes (like a yellow cell fill color).
7 Ways To Find The Last Row With VBA
There are actually quite a few ways to determine the last row of a data set in a spreadsheet. We will walk through a number of different ways in this article. I have marked specific methods with a “Best Method” tag as these coding practices are the most bullet-proof ways to determine the last row in your spreadsheet data.
1. The Find Function Method (Best Method)
This line of VBA code will search all the cells on your sheet and return the row of the last cell with any sort of value stored in it. Because the Find function is set to search from the very bottom of the spreadsheet and upwards, this code can accommodate blank rows within your data.
Dim LastRow As Long
LastRow = ActiveSheet.Cells.Find(«*», SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
2. SpecialCells Method
SpecialCells is a function you can call in VBA that will allow you to pinpoint certain cells or a range of cells based on specific criteria. We can use the xlCellTypeLastCell action to find the last cell in the spreadsheet and call for the cell’s row number.
Dim LastRow As Long
LastRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
WARNING! This method could give you unintended results as this finds the last cell with any sort of data or formatting associated with it. This means it can return an empty cell that used to have data in it or simply has any formatting changes (like a yellow cell fill color).
3. Ctrl+Shift+End Method
This line of VBA code mimics the keyboard shortcut Ctrl + Shift + End and returns the numerical value of the last row in the range.
Dim LastRow As Long
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, «A»).End(xlUp).Row
4. UsedRange Method
The Used Range is something that Excel stores a reference to behind the scenes. It represents the area of the spreadsheet that has values in it. The Used Range can be referenced in VBA using the UsedRange object.
You must be careful with the Used Range though , as Excel does not always update the reference in real time. Sometimes when you delete cell content the Used Range will not readjust itself right away. For this reason, it is wise to force the UsedRange object to restructure itself with your VBA code. The below VBA code example calls this restructure/refresh prior to utilizing UsedRange to pull the last row.
Dim LastRow As Long
ActiveSheet.UsedRange ‘Refresh UsedRange
LastRow = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row
5. Table Object Method (Best Method)
If you are using a Table Object to store your data, you can use the Table’s name in the below VBA code to return the numerical value of how many rows are in the table.
Dim LastRow As Long
LastRow = ActiveSheet.ListObjects(«Table1»).Range.Rows.Count
6. Named Range Method
If you are using a Named Range to reference your data’s location, you can use the Range name in the below VBA code to return the numerical value of how many rows are in the Named Range.
Dim LastRow As Long
LastRow = ActiveSheet.Range(«MyNamedRange»).Rows.Count
7. Ctrl+Shift+Down Method
Dim LastRow As Long
LastRow = ActiveSheet.Range(«A1»).CurrentRegion.Rows.Count
Expand Your Range To The Last Row
After you have determined the last row, how do you use it? The vast majority of the time you are going to want to store your entire data range to a Range variable. The following code shows you how to incorporate the last row number you calculated into a Range reference.
Dim DataRange As Range
Set DataRange = Range(«A1:M» & LastRow)
7 Ways To Find The Last Column With VBA
There are actually quite a few ways to determine the last column of a data set in a spreadsheet. We will walk through a number of different ways in this article. I have marked specific methods with a “Best Method” tag as these coding practices are the most bullet-proof ways to determine the last column in your spreadsheet data.
1. The Find Function Method (Best Method)
This line of VBA code will search all the cells on your sheet and return the column of the last cell with any sort of value stored in it. Because the Find function is set to search from the very far right of the spreadsheet and then leftward, this code can accommodate blank columns within your data.
Dim LastColumn As Long
LastColumn = ActiveSheet.Cells.Find(«*», SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
2. SpecialCells Method
SpecialCells is a function you can call in VBA that will allow you to pinpoint certain cells or a range of cells based on specific criteria. We can use the xlCellTypeLastCell action to find the last cell in the spreadsheet and call for the cell’s column number.
Dim LastColumn As Long
LastColumn = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column
WARNING! This method could give you unintended results as this finds the last cell with any sort of data or formatting associated with it. This means it can return an empty cell that used to have data in it or simply has any formatting changes (like a yellow cell fill color).
3. Ctrl+Shift+End Method
Dim LastColumn As Long
LastColumn = ActiveSheet.Cells(1, ActiveSheet.Columns.Count).End(xlToLeft).Column
4. UsedRange Method
Dim LastColumn As Long
ActiveSheet.UsedRange ‘Refresh UsedRange
LastColumn = ActiveSheet.UsedRange.Columns(ActiveSheet.UsedRange.Columns.Count).Column
5. Table Object Method (Best Method)
If you are using a Table Object to store your data, you can use the Table’s name in the below VBA code to return the numerical value of how many columns are in the table.
Dim LastColumn As Long
LastColumn = ActiveSheet.ListObjects(«Table1»).Range.Columns.Count
6. Named Range Method
Dim LastColumn As Long
LastColumn = ActiveSheet.Range(«MyNamedRange»).Columns.Count
7. Ctrl+Shift+Right Method
Dim LastColumn As Long
LastColumn = ActiveSheet.Range(«A1»).CurrentRegion.Columns.Count
How To Expand Your Range To The Last Column
After you have determined the last column, how do you use it? The vast majority of the time you are going to want to store your entire data range to a Range variable. The following code shows you how to incorporate the last column number you calculated into a Range reference.
Dim DataRange As Range
Set DataRange = Range(Cells(1, 1), Cells(100, LastColumn))
VBA Function To Find Last Row or Column
Tim provided the inspiration for a function that can return either the last row or column number through a user-defined function for a given worksheet.
An example of how you could call this function to return the last row on the active worksheet would be written as: x = LastRowColumn(ActiveSheet, «Row»)
Function LastRowColumn(sht As Worksheet, RowColumn As String) As Long
‘PURPOSE: Function To Return the Last Row Or Column Number In the Active Spreadsheet
‘INPUT: «R» or «C» to determine which direction to search
Select Case LCase(Left(RowColumn, 1)) ‘If they put in ‘row’ or column instead of ‘r’ or ‘c’.
Case «c»
LastRowColumn = sht.Cells.Find(«*», LookIn:=xlFormulas, SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
Case «r»
LastRowColumn = sht.Cells.Find(«*», LookIn:=xlFormulas, SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
Case Else
LastRowColumn = 1
End Select
End Function
What Can I Do With A LastRow Or LastColumn Variable?
There are many things you can do by calculating the last row or last column of a data set. Examples could be:
-
Resizing a Pivot Table range
-
Looping through cells in a column
-
Deleting only the raw data range
There are many, many more examples of this and I’m sure you can think of a few examples yourself.
Let me know in the comments section below how you use resizing a range in your macro code! Also, if you can think of any other ways to use VBA code to find the last row or last column, post your coding method in the comments section so we can improve the current list. I look forward to reading about your experiences.
I Hope This Excel Tutorial Helped!
Hopefully, I was able to explain how you can use VBA code to find the last row or last column of your range to add dynamic capabilities to your macros. If you have any questions about these techniques or suggestions on how to improve this article, please let me know in the comments section below.
About The Author
Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.
Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and hope to see you back here soon! — Chris
На чтение 10 мин. Просмотров 47.6k.
Итог: узнаете, как найти последнюю строку, столбец или ячейку в таблице с использованием трех различных методов на VBA. Используемый метод зависит от макета данных и от того, содержит ли лист пустые ячейки.
Уровень мастерства: средний
Видео: 3 части серии как найти последнюю ячейку с VBA
Видео лучше всего просматривать в полноэкранном режиме HD
Загрузите файл, содержащий код:
Find Last Cell VBA Примеры.xlsm (79.6 KB)
Поиск последней ячейки — все о данных
Поиск последней используемой строки, столбца или ячейки — это одна из самых распространенных задач при написании макросов и приложений VBA. Как и все в Excel и VBA, есть много различных способов.
Выбор правильного метода в основном зависит от того, как выглядят ваши данные.
В этой статье я объясняю три различных метода VBA объекта Range, которые мы можем использовать для поиска последней ячейки на листе. Каждый из этих методов имеет плюсы и минусы, а некоторые выглядят страшнее других. 🙂
Но понимание того, как работает каждый метод, поможет вам узнать, когда их использовать и почему.
#1 – The Range.End() Method
Range.End() очень похож на сочетание клавиш Ctrl+Arrow. В VBA можно использовать этот метод, чтобы найти последнюю не пустую ячейку в одной строке или столбце.
Диапазон.Пример кода End VBA
Sub Последняя_ячейка() 'Найти последнюю не пустую ячейку в одной строке или столбце Dim lRow As Long Dim lCol As Long 'Найти последнюю не пустую ячейку в столбце А(1) lRow = Cells(Rows.Count, 1).End(xlUp).Row 'Найти последнюю непустую ячейку в строке 1 lCol = Cells(1, Columns.Count).End(xlToLeft).Column MsgBox "Последняя строка: " & lRow & vbNewLine & _ "Последний столбец: " & lCol End Sub
Чтобы найти последнюю использованную строку в столбце, этот
метод начинается с последней ячейки столбца и идет вверх (xlUp), пока не найдет
первую непустую ячейку.
Оператор Rows.Count возвращает количество всех строк на рабочем листе. Поэтому мы в основном указываем последнюю ячейку в столбце A листа (ячейка A1048567) и поднимаемся до тех пор, пока не найдем первую непустую ячейку.
Это работает так же с поиском последнего столбца. Он начинается с последнего столбца в строке, затем идет влево, пока в столбце не будет найдена последняя непустая ячейка. Columns.Count возвращает общее количество столбцов на листе. Итак, мы начинаем с последнего столбца и идем налево.
Аргумент для метода End указывает, в каком направлении идти.
Возможные варианты: xlDown, xlUp, xlToLeft, xlToRight.
Плюсы Range.End
- Range.End прост в использовании и понимании, так как он работает так же, как сочетания клавиш Ctrl+Arrow.
- Может использоваться для поиска первой пустой ячейки или последней непустой ячейки в одной строке или столбце.
Минусы Range.End
- Range.End работает только с одной строкой или столбцом. При наличии диапазона данных, содержащего пробелы в последней строке или столбце, может быть трудно определить, в какой строке или столбце выполнять метод.
- Если вы хотите найти последнюю используемую ячейку, то вы должны оценить по крайней мере два оператора. Один, чтобы найти последнюю строку и один, чтобы найти последний столбец. Затем их можно объединить для ссылки на последнюю ячейку.
Вот справочные статьи для Range.End
- Страница справки MSDN для Range.End
- Справка MSDN для перечислений xlDirection
#2 – The Range.Find() Method
Метод Range.Find — я предпочитаю этот способ, чтобы найти последнюю строку, столбец или ячейку. Он самый универсальный, но и самый страшный.
У Range.Find много аргументов, но пусть это вас не пугает. Когда вы знаете, что они делают, вы можете использовать Range.Find для многих вещей в VBA.
Range.Find — это в основном способ программирования меню «Find» в Excel. Он делает то же самое, и большинство аргументов Range.Find являются опциями в меню Find.
Пример кода Range.Find
Ниже
приведен код для поиска последней непустой строки.
Sub Последняя_ячейка_Find() 'Находит последнюю непустую ячейку на листе / диапазоне. Dim lRow As Long Dim lCol As Long lRow = Cells.Find(What:="*", _ After:=Range("A1"), _ LookAt:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row MsgBox "Последняя строка: " & lRow End Sub
Метод Range.Find. Пояснения
Метод Find ищет первую непустую ячейку («*»). Звездочка представляет
собой символ подстановки, который ищет любой текст или числа в ячейке.
Начиная с ячейки A1, он перемещается назад (xlPrevious) и
фактически начинает поиск в самой последней ячейке на листе. Затем он
перемещается справа налево (xlByRows) и проходит по каждой строке, пока не
найдет непустую ячейку. При обнаружении непустого он останавливается и
возвращает номер строки.
Вот подробное объяснение каждого аргумента.
- What:=”*” — звездочка — это символ подстановки, который находит любой текст или число в ячейке. Это в основном то же самое, что и поиск непустой ячейки.
- After:=Range(“A1”)— начать поиск после ячейки А1, первой ячейки на листе. Это означает, что A1 не будет искать. Поиск начнется после A1, и следующая ячейка, которую он ищет, зависит от SearchOrder и SearchDirection. Этот аргумент можно изменить, чтобы он начинался в другой ячейке, просто помните, что поиск фактически начинается в ячейке после указанной.
- LookAt: = xlPart — это будет смотреть на любую часть текста внутри ячейки. Другой вариант — xlWhole, который будет пытаться соответствовать всему содержимому ячейки.
- LookIn: = xlFormulas — Это заставляет Find искать в формулах, и это важный аргумент. Другой вариант — xlValues, который будет искать только значения. Если у вас есть формулы, которые возвращают пробелы (= IF (A2> 5, «Ok», «»), то вы можете считать это непустой ячейкой. При указании LookIn в качестве xlFormulas эта формула будет считаться непустой, даже если возвращаемое значение пустое.
- SearchOrder: = xlByRows — это говорит Find, чтобы искать через каждую целую строку прежде, чем перейти к следующей. Направление поиска слева направо или справа налево зависит от аргумента SearchDirection. Другой вариант здесь — xlByColumns, который используется при поиске последнего столбца.
- SearchDirection: = xlPrevious — указывает направление поиска. xlPrevious означает, что он будет искать справа налево или снизу вверх. Другой вариант — xlNext, который перемещается в противоположном направлении.
- MatchCase: = False — это говорит Find, чтобы не рассматривать заглавные или строчные буквы. Если установить значение True, это поможет. Этот аргумент не является необходимым для этого сценария.
Да, я знаю, что это много, но надеюсь, у вас будет лучшее понимание того, как использовать эти аргументы, чтобы найти что-нибудь на листе.
Плюсы
Range.Find
- Find ищет во всем диапазоне последнюю непустую строку или столбец. Он НЕ ограничен одной строкой или столбцом.
- Последняя строка в наборе данных может содержать пробелы, и Range.Find все равно найдет последнюю строку.
- Аргументы могут использоваться для поиска в разных направлениях и для определенных значений, а не только пустых ячеек.
Минусы Range.Find
- Это ужасно. Метод содержит 9 аргументов. Хотя требуется только один из этих аргументов (Что), вы должны привыкнуть использовать хотя бы первые 7 аргументов. В противном случае метод Range.Find по умолчанию будет использовать ваши последние использованные настройки в окне поиска. Это важно. Если вы не укажете необязательные аргументы для LookAt, LookIn и SearchOrder, тогда метод Find будет использовать те параметры, которые вы использовали последними в окне поиска Excel.
- Нахождение последней ячейки требует двух утверждений. Один, чтобы найти последний ряд и один, чтобы найти последний столбец. Затем вы должны объединить их, чтобы найти последнюю ячейку.
Macro Recorder выручит!
Range.Find — все еще мой любимый метод для нахождения последней ячейки из-за ее универсальности. Но нужно много напечатать и запомнить. К счастью, вам это не нужно.
Вы можете использовать макро рекордер, чтобы быстро создать код со всеми аргументами.
- Запустить макро рекордер
- Нажмите Ctrl + F
- Затем нажмите кнопку «Найти далее»
Код для метода Find со всеми аргументами будет сгенерирован устройством записи макросов.
Используйте пользовательскую функцию для метода Find
Вы также можете использовать пользовательскую функцию (UDF) для метода поиска. Последняя функция Ron de Bruin — прекрасный пример. Вы можете скопировать эту функцию в любой проект или модуль кода VBA и использовать ее для возврата последней строки, столбца или ячейки.
У меня также есть аналогичная функция в примере рабочей книги. Моя функция просто имеет дополнительные аргументы для ссылки на лист и диапазон для поиска.
Вот справочные статьи для Range.Find
- MSDN Help Article for Range.Find Method
#3 – Range.SpecialCells (xlCellTypeLastCell)
Метод SpecialCells делает то же самое, что и нажатие сочетания клавиш Ctrl + End, и выбирает последнюю использованную ячейку на листе.
Пример кода SpecialCells (xlCellTypeLastCell)
Sub Range_SpecialCells_Method() MsgBox Range("A1").SpecialCells(xlCellTypeLastCell).Address End Sub
На самом деле это самый простой способ найти последнюю использованную ячейку. Однако этот метод находит последнюю использованную ячейку, которая может отличаться от последней непустой ячейки.
Часто вы будете нажимать Ctrl + End на клавиатуре и попадете в какую-нибудь ячейку вниз в конце листа, который определенно не используется. Это может произойти по ряду причин. Одной из распространенных причин является то, что свойства форматирования для этой ячейки были изменены. Простое изменение размера шрифта или цвета заливки ячейки помечает ее как использованную ячейку.
Плюсы Range.SpecialCells
- Вы можете использовать этот метод, чтобы найти «используемые» строки и столбцы в конце листа и удалить их. Сравнение результата Range.SpecialCells с результатом Range.Find для непробелов может позволить вам быстро определить, существуют ли какие-либо неиспользуемые строки или столбцы на листе.
- Удаление неиспользуемых строк / столбцов может уменьшить размер файла и увеличить полосу прокрутки.
Минусы Range.SpecialCells
- Excel только сбрасывает последнюю ячейку при сохранении книги. Поэтому, если пользователь или макрос удаляет содержимое некоторых ячеек, этот метод не найдет истинную последнюю ячейку, пока файл не будет сохранен.
- Он находит последнюю использованную ячейку, а НЕ последнюю непустую ячейку.
Другие методы поиска последней ячейки
Что ж, это должно охватывать основы поиска последней
использованной или непустой ячейки на листе. Если ваш лист содержит объекты
(таблицы, диаграммы, сводные таблицы, слайсеры и т. Д.), Вам может
потребоваться использовать другие методы для поиска последней ячейки. Я объясню
эти методы в отдельном посте.
У меня также есть статья о том, как найти ПЕРВУЮ ячейку в листе.
Пожалуйста, оставьте комментарий ниже, если у вас есть какие-либо вопросы, или вы все еще не можете найти последнюю ячейку. Я буду рад помочь!
Поиск номера последней заполненной строки с помощью кода VBA Excel для таблиц, расположенных как в верхнем левом углу, так и в любом месте рабочего листа.
Номер последней заполненной строки в таблице Excel обычно используется в коде VBA для определения следующей за ней первой пустой строки для добавления новой записи. А также для задания интервала для поиска и обработки информации с помощью цикла For… Next (указание границ обрабатываемого диапазона).
Переменную, которой присваивается номер последней строки, следует объявлять как Long или Variant, например: Dim PosStr As Long
. В современных версиях Excel количество строк на рабочем листе превышает максимальное значение типа данных Integer.
Таблица в верхнем левом углу
В первую очередь рассмотрим все доступные варианты поиска номера последней заполненной строки для таблиц, расположенных в верхнем левом углу рабочего листа. Такие таблицы обычно представляют собой простые базы данных в Excel, или, как их еще называют, наборы записей.
Пример таблицы с набором данных в Excel
Вариант 1
Основная формула для поиска последней строки в такой таблице, не требующая соблюдения каких-либо условий:
PosStr = Cells(1, 1).CurrentRegion.Rows.Count
Вариант 2
Ниже таблицы не должно быть никаких записей, в том числе ранее удаленных:
PosStr = ActiveSheet.UsedRange.Rows.Count
Вариант 3
В первом столбце таблицы не должно быть пропусков, а также в таблице должно быть не менее двух заполненных строк, включая строку заголовков:
PosStr = Cells(1, 1).End(xlDown).Row
Вариант 4
В первой колонке рабочего листа внутри таблицы не должно быть пропусков, а ниже таблицы в первой колонке не должно быть других заполненных ячеек:
PosStr = WorksheetFunction.CountA(Range("A:A"))
Вариант 5
Ниже таблицы не должно быть никаких записей:
PosStr = Cells.SpecialCells(xlLastCell).Row
Последняя строка любой таблицы
Последнюю заполненную строку для любой таблицы будем искать, отталкиваясь от ее верхней левой ячейки: Cells(a, b)
.
Вариант 1
Основная формула для поиска последней строки в любой таблице, не требующая соблюдения каких-либо условий:
PosStr = Cells(a, b).CurrentRegion.Cells(Cells(a, b).CurrentRegion.Cells.Count).Row
Вариант 2
Дополнительная формула с условием, что в первом столбце таблицы нет пустых ячеек:
PosStr = Cells(a, b).End(xlDown).Row
Если у вас на рабочем листе Excel есть записи вне таблиц, следите за тем, чтобы таблицы были окружены пустыми ячейками или пустыми ячейками и границами листа. Тогда не будет случайно внесенных заметок, примыкающих к таблицам, которые могут отрицательно повлиять на точность вычисления номера последней строки из кода VBA.
Excel VBA Last Row
Finding the last row in a column is an important aspect in writing macro’s and making those dynamic. As we would not prefer to update the cell ranges every now and then when we are working with Excel cell references. As being a coder/developer, you would always prefer to write a dynamic code which can be used on any data and suffice your requirement. Moreover, it would always be great if you have the last row known of your data so that you can dynamically change the code as per your requirement.
I will just point out one example which iterates the importance of dynamic code.
Suppose I have data as given below with employee and their salaries.
And look at the code given below:
Code:
Sub Example1() Range("D2").Value = WorksheetFunction.Sum(Range("B2:B11")) End Sub
Here, this code prints the sum of salaries for all employees (cell B2:B11) in cell D2. See the image below:
Now, what if I add some cells to this data and run this code again?
Logically speaking, the above code will not sum up all the 14 rows from column B. Reason for the same is the range which we have updated under WorksheetFunction (which is B2:B11). This is the reason a dynamic code which can take the last filled row into consideration makes it more important for us.
In this article, I will introduce some methods which can be useful in finding out the last row for a given data set using VBA code.
How to Find Last used Row in Column Using VBA?
Below are the different examples with different methods to find the last used Row of a Column in Excel using VBA Code.
You can download this VBA Last Row Excel Template here – VBA Last Row Excel Template
Example #1 – Using Range.End() Method
Well, this method is as same as using the Ctrl + Down Arrow in Excel to go to the last non-empty row. On similar lines, follow the below steps for creating code in VBA to reach to the last non-empty row of a column in Excel.
Step 1: Define a variable which can take value for the last non-empty row of the excel column.
Code:
Sub Example2() Dim Last_Row As Long End Sub
Here, the variable Last_Row is defined as LONG just to make sure it can take any number of arguments.
Step 2: Use the defined variable to hold the value of the last non-empty row.
Code:
Sub Example2() Dim Last_Row As Long Last_Row = End Sub
Step 3: Type the code starting with CELLS (Rows.Count in front of Last_Row =.
Code:
Sub Example2() Dim Last_Row As Long Last_Row = Cells(Rows.Count End Sub
Step 4: Mention 1 after a comma in the above-mentioned code. The value numeric 1 is synonyms to the first column in the excel sheet.
Code:
Sub Example2() Dim Last_Row As Long Last_Row = Cells(Rows.Count, 1) End Sub
This code allows VBA to find out the total number of (empty + non-empty) rows present in the first column of the excel worksheet. This means this code allows the system to go to the last cell of Excel.
Now, what if you are at the last cell of the excel and want to go up to the last non-empty row? You’ll use Ctrl + Up Arrow, right?
The same logic we are going to use in the next line of code.
Step 5: Use a combination of End key and xlUp to go to the last non-empty row in excel.
Code:
Sub Example2() Dim Last_Row As Long Last_Row = Cells(Rows.Count, 1).End(xlUp) End Sub
This will take you to the last non-empty row in the excel. However, you wanted a row number for the same.
Step 6: Use ROW to get the row number of the last non-empty row.
Code:
Sub Example2() Dim Last_Row As Long Last_Row = Cells(Rows.Count, 1).End(xlUp).Row End Sub
Step 7: Show the value of Last_Row, which contains the last non-empty row number using MsgBox.
Code:
Sub Example2() Dim Last_Row As Long Last_Row = Cells(Rows.Count, 1).End(xlUp).Row MsgBox Last_Row End Sub
Step 8: Run the code using the Run button or hitting F5 and see the output.
Output:
Step 9: Now, let’s delete one row and see if the code gives an accurate result or not. It will help us checking the dynamism of our code.
Example #2 – Using Range and SpecialCells
We can also use the Range and SepcialCells property of VBA to get the last non-empty row of the excel sheet.
Follow the below steps to get the last non-empty row in excel using VBA code:
Step 1: Define a variable again as Long.
Code:
Sub Example3() Dim Last_Row As Long End Sub
Step 2: Start storing the value to the variable Last_Row using the assignment operator.
Code:
Sub Example3() Dim Last_Row As Long Last_Row = End Sub
Step 3: Start Typing Range(“A:A”).
Code:
Sub Example3() Dim Last_Row As Long Last_Row = Range("A:A") End Sub
Step 4: Use the SpecialCells function to find out the last non-empty cell.
Code:
Sub Example3() Dim Last_Row As Long Last_Row = Range("A:A").SpecialCells(xlCellTypeLastCell) End Sub
This function SpecialCells selects the last cell from your excel as it is written in the parentheses (xlCellTypeLastCell allows you to select the last non-empty cell from your excel sheet).
Step 5: Now, use ROW to get the last row from your excel sheet.
Code:
Sub Example3() Dim Last_Row As Long Last_Row = Range("A:A").SpecialCells(xlCellTypeLastCell).Row End Sub
This will return the last non-empty row for you from your excel.
Step 6: Now, assign this value of Last_Row to MsgBox so that we can see the last non-empty row number on the message box.
Code:
Sub Example3() Dim Last_Row As Long Last_Row = Range("A:A").SpecialCells(xlCellTypeLastCell).Row MsgBox Last_Row End Sub
Step 7: Run the code by hitting the F5 or Run button placed at the top of the left corner.
Output:
You can see that the last non-empty cell number is popped out through MsgBox with reference to the column A because we have mentioned the column A under the Range function while defining the variable formula.
Step 8: If we delete a row and can run this formula. Let’s see what happens.
You can see the system has still given a row count of 14. Even though I have deleted a row and the actual row count is 13, the system has not captured the row count accurately. For the system to capture the actual row count, you need to save the worksheet and run the code again.
You can see the actual row count is showing in this screenshot now.
Example #3 – Using Range.Find()
Follow the below steps to get the last non-empty row in excel using VBA code:
Step 1: Define a variable as long.
Code:
Sub Example4() Dim Last_Row As Long End Sub
Step 2: Now, use the following code to see the last non-empty row.
Code:
Sub Example4() Dim Last_Row As Long Last_Row = Cells.Find(What:="*", _ After:=Range("A1"), _ LookAt:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row End Sub
Here, the FIND function looks for the first non-blank cell. Asterisk (*) is a wildcard operator which helps in finding out the same.
Starting from cell A1, the system goes back to the last cell from the sheet and searches in a backward direction (xlPrevious). It moves from right to left (xlByRows) and loops up in the same sheet through all the rows on similar lines until it finds a non-blank row (see the .ROW at the end of the code).
Step 3: Use MsgBox to store the value of the last non-empty row and see it as a pop-up box.
Code:
Sub Example4() Dim Last_Row As Long Last_Row = Cells.Find(What:="*", _ After:=Range("A1"), _ LookAt:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row MsgBox Last_Row End Sub
Step 4: Run the code and see the output as a pop-up box containing the last non-empty row number.
Output:
Things to Remember
- End (Example1) can be used to find out the first blank cell/row or last non-empty cell/row in a given column using the VBA code.
- The end works on a single column most of the time. If you have data in ranges, it would be difficult to decide which column should be used to find out the last non-empty row.
- Find (Example3) works on an entire range from the point of start and finds out the last non-empty cell/row in a given column using VBA code. It also can be used to find out the last non-empty column.
Recommended Articles
This is a guide to VBA Last Row. Here we discuss how to find the last used row in a given column along with some practical examples and a downloadable excel template. You may also look at the following articles to learn more –
- VBA Insert Column
- VBA Range Cells
- VBA XML
- VBA XLUP
We use Range.SpecialCells() method in the below VBA Code to find and return details of last used row, column, and cell in a worksheet.
Sample Data:
Sample Data
Syntax:
expression.SpecialCells (Type, Value)
Eg: To return the last used cell address in an activesheet. ActiveSheet.Range(“A1”).SpecialCells(xlCellTypeLastCell).Address
VBA Code:
Declaring Variables:
Variable | Data Type | Comments |
---|---|---|
LastRow | Long | Find and store last used row |
LastCol | Long | store last used column |
LastCell | String | store last used cell address |
'Variable Declaration Dim LastRow As Long, LastCol As Long, LastCell As String
Use SpecialCells function to find last used row/column/cell
'Find Last Used Row LastRow = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Row 'Find Last Used Column LastCol = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Column 'Find Last Used Cell LastCell = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Address
Concatenate all three variables (LastRow/LastCol/LastCell), add a new line between variables use Chr(10). Show the final output in an Excel Message box.
'Display the last used row/column/cell MsgBox "Last Used Row : " & LastRow & Chr(10) & "Last Used Column : " & LastCol & Chr(10) & "Last Used Cell : " & LastCell
Implementation:
Follow the below steps to find the Last Used Row and Last Used Column in Excel VBA
Step 1: Add a shape (Find Last Row/Column/Cell) on your worksheet.
Step 2: Right-click on “Find Last Row/Column/Cell” and “Assign Macro..”
Step 3: Select “findLastUsedCell”, you can see a list of macros if available in your workbook
Step 4: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm
Step 5: Click “Find Last Row/Column/Cell” to execute the VBA code. Code will popup below output for the above given example (Output).
Output:
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.
замечания
Найдите последнюю непустую ячейку в столбце
В этом примере мы рассмотрим метод возврата последней непустой строки в столбец для набора данных.
Этот метод будет работать независимо от пустых областей в наборе данных.
Однако следует соблюдать осторожность, если задействованы объединенные ячейки , поскольку метод End
будет «остановлен» против объединенной области, возвращая первую ячейку объединенной области.
Кроме того, непустые ячейки в скрытых строках не будут учитываться.
Sub FindingLastRow()
Dim wS As Worksheet, LastRow As Long
Set wS = ThisWorkbook.Worksheets("Sheet1")
'Here we look in Column A
LastRow = wS.Cells(wS.Rows.Count, "A").End(xlUp).Row
Debug.Print LastRow
End Sub
Чтобы устранить указанные выше ограничения, строка:
LastRow = wS.Cells(wS.Rows.Count, "A").End(xlUp).Row
могут быть заменены на:
-
для последнего использованного ряда
"Sheet1"
:
LastRow = wS.UsedRange.Row - 1 + wS.UsedRange.Rows.Count
. -
для последней непустой ячейки столбца
"A"
в"Sheet1"
:Dim i As Long For i = LastRow To 1 Step -1 If Not (IsEmpty(Cells(i, 1))) Then Exit For Next i LastRow = i
Найти последнюю строку с использованием именованного диапазона
Если у вас есть Именованный диапазон в вашем листе, и вы хотите динамически получить последнюю строку этого динамического именованного диапазона. Также охватывает случаи, когда Named Range не начинается с первой строки.
Sub FindingLastRow()
Dim sht As Worksheet
Dim LastRow As Long
Dim FirstRow As Long
Set sht = ThisWorkbook.Worksheets("form")
'Using Named Range "MyNameRange"
FirstRow = sht.Range("MyNameRange").Row
' in case "MyNameRange" doesn't start at Row 1
LastRow = sht.Range("MyNameRange").Rows.count + FirstRow - 1
End Sub
Обновить:
Потенциальная лазейка была отмечена @Jeeped для aa named range с несмежными строками, поскольку она генерирует неожиданный результат. Чтобы решить эту проблему, код пересматривается, как показано ниже.
Апппции: таргеты sheet = form
, named range = MyNameRange
Sub FindingLastRow()
Dim rw As Range, rwMax As Long
For Each rw In Sheets("form").Range("MyNameRange").Rows
If rw.Row > rwMax Then rwMax = rw.Row
Next
MsgBox "Last row of 'MyNameRange' under Sheets 'form': " & rwMax
End Sub
Получить строку последней ячейки в диапазоне
'if only one area (not multiple areas):
With Range("A3:D20")
Debug.Print .Cells(.Cells.CountLarge).Row
Debug.Print .Item(.Cells.CountLarge).Row 'using .item is also possible
End With 'Debug prints: 20
'with multiple areas (also works if only one area):
Dim rngArea As Range, LastRow As Long
With Range("A3:D20, E5:I50, H20:R35")
For Each rngArea In .Areas
If rngArea(rngArea.Cells.CountLarge).Row > LastRow Then
LastRow = rngArea(rngArea.Cells.CountLarge).Row
End If
Next
Debug.Print LastRow 'Debug prints: 50
End With
Найти последнюю непустую колонку в рабочем листе
Private Sub Get_Last_Used_Row_Index()
Dim wS As Worksheet
Set wS = ThisWorkbook.Sheets("Sheet1")
Debug.Print LastCol_1(wS)
Debug.Print LastCol_0(wS)
End Sub
Вы можете выбрать один из двух вариантов, если хотите узнать, нет ли данных на листе:
- НЕТ: Используйте LastCol_1: вы можете использовать его непосредственно в
wS.Cells(...,LastCol_1(wS))
- ДА: Использовать LastCol_0: вам нужно проверить, если результат, полученный вами от функции, равен 0 или нет, прежде чем использовать его
Public Function LastCol_1(wS As Worksheet) As Double
With wS
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
LastCol_1 = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Else
LastCol_1 = 1
End If
End With
End Function
Свойства объекта Err автоматически сбрасываются до нуля после выхода функции.
Public Function LastCol_0(wS As Worksheet) As Double
On Error Resume Next
LastCol_0 = wS.Cells.Find(What:="*", _
After:=ws.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
End Function
Последняя ячейка в Range.CurrentRegion
Range.CurrentRegion
— прямоугольная область диапазона, окруженная пустыми ячейками. Пустые ячейки с такими формулами, как =""
или '
, не считаются пустыми (даже ISBLANK
Excel).
Dim rng As Range, lastCell As Range
Set rng = Range("C3").CurrentRegion ' or Set rng = Sheet1.UsedRange.CurrentRegion
Set lastCell = rng(rng.Rows.Count, rng.Columns.Count)
Найти последнюю непустую строку в рабочем листе
Private Sub Get_Last_Used_Row_Index()
Dim wS As Worksheet
Set wS = ThisWorkbook.Sheets("Sheet1")
Debug.Print LastRow_1(wS)
Debug.Print LastRow_0(wS)
End Sub
Вы можете выбрать один из двух вариантов, если хотите узнать, нет ли данных на листе:
- НЕТ: Используйте LastRow_1: вы можете использовать его непосредственно в
wS.Cells(LastRow_1(wS),...)
- YES: Использовать LastRow_0: вам нужно проверить, есть ли результат, полученный вами от функции, 0 или нет, прежде чем использовать его
Public Function LastRow_1(wS As Worksheet) As Double
With wS
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
LastRow_1 = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
LastRow_1 = 1
End If
End With
End Function
Public Function LastRow_0(wS As Worksheet) As Double
On Error Resume Next
LastRow_0 = wS.Cells.Find(What:="*", _
After:=ws.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End Function
Найти последнюю непустую ячейку в строке
В этом примере мы рассмотрим метод возврата последнего непустого столбца в строке.
Этот метод будет работать независимо от пустых областей в наборе данных.
Однако следует соблюдать осторожность, если задействованы объединенные ячейки , поскольку метод End
будет «остановлен» против объединенной области, возвращая первую ячейку объединенной области.
Кроме того, непустые ячейки в скрытых столбцах не будут учитываться.
Sub FindingLastCol()
Dim wS As Worksheet, LastCol As Long
Set wS = ThisWorkbook.Worksheets("Sheet1")
'Here we look in Row 1
LastCol = wS.Cells(1, wS.Columns.Count).End(xlToLeft).Column
Debug.Print LastCol
End Sub
Найти последнюю непустую ячейку в рабочем листе — Производительность (массив)
- Первая функция, использующая массив, намного быстрее
- Если
.ThisWorkbook.ActiveSheet
без необязательного параметра, по умолчанию будет.ThisWorkbook.ActiveSheet
- Если диапазон пуст, он будет возвращать
Cell( 1, 1 )
по умолчанию вместоNothing
Скорость:
GetMaxCell (Array): Duration: 0.0000790063 seconds
GetMaxCell (Find ): Duration: 0.0002903480 seconds
. Измеряется с помощью MicroTimer
Public Function GetLastCell(Optional ByVal ws As Worksheet = Nothing) As Range
Dim uRng As Range, uArr As Variant, r As Long, c As Long
Dim ubR As Long, ubC As Long, lRow As Long
If ws Is Nothing Then Set ws = Application.ThisWorkbook.ActiveSheet
Set uRng = ws.UsedRange
uArr = uRng
If IsEmpty(uArr) Then
Set GetLastCell = ws.Cells(1, 1): Exit Function
End If
If Not IsArray(uArr) Then
Set GetLastCell = ws.Cells(uRng.Row, uRng.Column): Exit Function
End If
ubR = UBound(uArr, 1): ubC = UBound(uArr, 2)
For r = ubR To 1 Step -1 '----------------------------------------------- last row
For c = ubC To 1 Step -1
If Not IsError(uArr(r, c)) Then
If Len(Trim$(uArr(r, c))) > 0 Then
lRow = r: Exit For
End If
End If
Next
If lRow > 0 Then Exit For
Next
If lRow = 0 Then lRow = ubR
For c = ubC To 1 Step -1 '----------------------------------------------- last col
For r = lRow To 1 Step -1
If Not IsError(uArr(r, c)) Then
If Len(Trim$(uArr(r, c))) > 0 Then
Set GetLastCell = ws.Cells(lRow + uRng.Row - 1, c + uRng.Column - 1)
Exit Function
End If
End If
Next
Next
End Function
'Returns last cell (max row & max col) using Find
Public Function GetMaxCell2(Optional ByRef rng As Range = Nothing) As Range 'Using Find
Const NONEMPTY As String = "*"
Dim lRow As Range, lCol As Range
If rng Is Nothing Then Set rng = Application.ThisWorkbook.ActiveSheet.UsedRange
If WorksheetFunction.CountA(rng) = 0 Then
Set GetMaxCell2 = rng.Parent.Cells(1, 1)
Else
With rng
Set lRow = .Cells.Find(What:=NONEMPTY, LookIn:=xlFormulas, _
After:=.Cells(1, 1), _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByRows)
If Not lRow Is Nothing Then
Set lCol = .Cells.Find(What:=NONEMPTY, LookIn:=xlFormulas, _
After:=.Cells(1, 1), _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByColumns)
Set GetMaxCell2 = .Parent.Cells(lRow.Row, lCol.Column)
End If
End With
End If
End Function
,
MicroTimer :
Private Declare PtrSafe Function getFrequency Lib "Kernel32" Alias "QueryPerformanceFrequency" (cyFrequency As Currency) As Long
Private Declare PtrSafe Function getTickCount Lib "Kernel32" Alias "QueryPerformanceCounter" (cyTickCount As Currency) As Long
Function MicroTimer() As Double
Dim cyTicks1 As Currency
Static cyFrequency As Currency
MicroTimer = 0
If cyFrequency = 0 Then getFrequency cyFrequency 'Get frequency
getTickCount cyTicks1 'Get ticks
If cyFrequency Then MicroTimer = cyTicks1 / cyFrequency 'Returns Seconds
End Function