За определенный период времени ведется регистр количества проданного товара в магазине. Необходимо регулярно отслеживать последний выданный из магазина товар. Для этого нужно отобразить последнюю запись в столбце наименования товаров. Чтобы просто посмотреть на последнее значение столбца, достаточно переместить курсор на любую его ячейку и нажать комбинацию горячих клавиш CTRL + стрелка в низ (↓). Но чаще всего пользователю приходится с последним значением столбца выполнять различные вычислительные операции в Excel. Поэтому лучше его получить в качестве значения для отдельной ячейки.
Поиск последнего значения в столбце Excel
Схематический регистр товаров, выданных с магазина:
Чтобы иметь возможность постоянно наблюдать, какой товар зарегистрирован последним, в отдельную ячейку E1 введем формулу:
Результат выполнения формулы для получения последнего значения:
Разбор принципа действия формулы для поиска последнего значения в столбце:
Главную роль берет на себя функция =ИНДЕКС(), которая должна возвращать содержимое ячейки таблицы где пересекаются определенная строка и столбец. В качестве первого аргумента функции ИНДЕКС выступает неизменяемая константа, а именно ссылка на целый столбец (B:B). Во втором аргументе находится номер строки с последним заполненным значением столбца B. Чтобы узнать этот номер строки используется функция СЧЁТЗ, которая возвращает количество непустых ячеек в диапазоне. Соответственно это же число равно номеру последней непустой строки в столбце B и используется как второй аргумент для функции ИНДЕКС, которая сразу возвращает последнее значение столбца B в отдельной ячейке E1.
Внимание! Все записи в столбце B должны быть неразрывны (без пустых ячеек до последнего значения).
Стоит отметить что данная формула является динамической. При добавлении новых записей в столбец B результат в ячейке E1 будет автоматически обновляться.
I’ve found this method for finding the last data containing row in a sheet:
ws.Range("A65536").End(xlUp).row
Is there a similar method for finding the last data containing column in a sheet?
jamheadart
4,9584 gold badges29 silver badges62 bronze badges
asked Aug 13, 2012 at 0:33
4
Lots of ways to do this. The most reliable is find.
Dim rLastCell As Range
Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
MsgBox ("The last used column is: " & rLastCell.Column)
If you want to find the last column used in a particular row you can use:
Dim lColumn As Long
lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
Using used range (less reliable):
Dim lColumn As Long
lColumn = ws.UsedRange.Columns.Count
Using used range wont work if you have no data in column A. See here for another issue with used range:
See Here regarding resetting used range.
answered Aug 13, 2012 at 2:00
ReafidyReafidy
8,2505 gold badges49 silver badges81 bronze badges
8
I know this is old, but I’ve tested this in many ways and it hasn’t let me down yet, unless someone can tell me otherwise.
Row number
Row = ws.Cells.Find(What:="*", After:=[A1] , SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Column Letter
ColumnLetter = Split(ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Cells.Address(1, 0), "$")(0)
Column Number
ColumnNumber = ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
answered Apr 19, 2016 at 11:52
xn1xn1
4174 silver badges12 bronze badges
Try using the code after you active the sheet:
Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
If you use Cells.SpecialCells(xlCellTypeLastCell).Row
only, the problem will be that the xlCellTypeLastCell
information will not be updated unless one do a «Save file» action. But use UsedRange
will always update the information in realtime.
Rob
4,91712 gold badges52 silver badges54 bronze badges
answered May 22, 2013 at 6:55
PeterPeter
211 bronze badge
1
I think we can modify the UsedRange
code from @Readify’s answer above to get the last used column even if the starting columns are blank or not.
So this lColumn = ws.UsedRange.Columns.Count
modified to
this lColumn = ws.UsedRange.Column + ws.UsedRange.Columns.Count - 1
will give reliable results always
?Sheet1.UsedRange.Column + Sheet1.UsedRange.Columns.Count - 1
Above line Yields 9
in the immediate window.
answered Mar 11, 2016 at 16:36
Stupid_InternStupid_Intern
3,3628 gold badges36 silver badges74 bronze badges
Here’s something which might be useful. Selecting the entire column based on a row containing data, in this case i am using 5th row:
Dim lColumn As Long
lColumn = ActiveSheet.Cells(5, Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)
answered Jun 27, 2018 at 9:09
dapazdapaz
80310 silver badges16 bronze badges
2
I have been using @Reafidy method/answer for a long time, but today I ran into an issue with the top row being merged cell from A1—>N1 and my function returning the «Last Column» as 1 not 14.
Here is my modified function now account for possibly merged cells:
Public Function Get_lRow(WS As Worksheet) As Integer
On Error Resume Next
If Not IsWorksheetEmpty(WS) Then
Get_lRow = WS.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Dim Cell As Range
For Each Cell In WS.UsedRange
If Cell.MergeCells Then
With Cell.MergeArea
If .Cells(.Cells.Count).Row > Get_lRow Then Get_lRow = .Cells(.Cells.Count).Row
End With
End If
Next Cell
Else
Get_lRow = 1
End If
End Function
Public Function Get_lCol(WS As Worksheet) As Integer
On Error Resume Next
If Not IsWorksheetEmpty(WS) Then
Get_lCol = WS.Cells.Find(What:="*", after:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Dim Cell As Range
For Each Cell In WS.UsedRange
If Cell.MergeCells Then
With Cell.MergeArea
If .Cells(.Cells.Count).Column > Get_lCol Then Get_lCol = .Cells(.Cells.Count).Column
End With
End If
Next Cell
Else
Get_lCol = 1
End If
End Function
answered Nov 8, 2021 at 19:41
Here’s a simple option if your data starts in the first row.
MsgBox "Last Row: " + CStr(Application.WorksheetFunction.CountA(ActiveSheet.Cells(1).EntireRow))
It just uses CountA
to count the number of columns with data in the entire row.
This has all sorts of scenarios where it won’t work, such as if you have multiple tables sharing the top row, but for a few quick & easy things it works perfect.
answered Dec 3, 2021 at 19:32
Alex KwitnyAlex Kwitny
10.9k2 gold badges48 silver badges70 bronze badges
How to find the last column in a row that has data. This includes selecting that column or a cell in it, returning the column number, and getting data from that column.
Sections:
Find the Last Column with Data
Select the Last Cell
Select the Entire Column
Get the Number of the Last Column
Get the Data from the Last Column
Notes
Find the Last Column with Data
Cells(1, Columns.Count).End(xlToLeft)
All you have to change to make this work for you is the 1.
This is the basic method that you use to return the last cell in a row that has data. That means that the cell will be in the last column that has data.
The 1 in the above code is the number of the row that you want to use when searching for the last column that has data. Currently, this code looks in row 1 and finds the last column in row 1 that has data. Change this to any number you want.
This doesn’t seem very useful right now, but, in practice, it is often used within a loop that goes through a list of rows and you can then set this code to find the last column of data for each row without having to manually change this number.
Columns.Count puts the total number of columns in for that argument of the Cells() function. This tells Excel to go to the very last cell in the row, all the way to the right.
Then, End(xlToLeft) tells Excel to go to the left from that last cell until it hits a cell with data in it.
This basic format is also used to find the last row in a column.
Now, let’s look at how to get useful information from this code.
Select the Last Cell
The first thing that you might want to do is to select the cell that has data in the last column of a row.
Cells(1, Columns.Count).End(xlToLeft).Select
Select is what selects that last cell in the row that has data.
This is exactly the same as the first piece of code except we added Select to the end of it.
1 is the row that is being checked.
Select the Entire Column
This selects the entire column where the last cell with data is found within a particular row.
Cells(1, Columns.Count).End(xlToLeft).EntireColumn.Select
EntireColumn is added to the base code and that is what references, well, the entire column.
Select is added to the end of EntireColumn and that is what does the actual «selecting» of the column.
1 is the row that is being checked.
Get the Number of the Last Column
Let’s get the number of the last column with data. This makes it easier to do things with that column, such as move one to the right of it to find the next empty cell in a row.
Cells(1, Columns.Count).End(xlToLeft).Column
Column is appended to the original code in order to give us the number of the column that contains the last piece of data in a row.
This is rather useless on its own though, so let’s put it into a variable so it can be used throughout the macro.
last_col = Cells(1, Columns.Count).End(xlToLeft).Column
The number of the last column is now stored in the variable last_col and you can now use that variable to reference this number.
1 is the row that is being checked.
Get the Data from the Last Column
Return any data contained in the cell in the last column.
Cells(1, Columns.Count).End(xlToLeft).Value
Value is added to the end of the base code in order to get the contents of the cell.
This is rather useless in its current form so let’s put it into a variable.
cell_value = Cells(1, Columns.Count).End(xlToLeft).Value
Now, the variable cell_value will contain anything that is in the last cell in the row.
1 is the row that is being checked.
Notes
The basic format for finding the last cell that has data in a row is the same and is the most important part to remember. Each piece of information that we want to get from that last cell simply requires one or two things to be added to the end of that base code.
Download the attached file to work with these examples in Excel.
Similar Content on TeachExcel
Get the Last Row using VBA in Excel
Tutorial:
(file used in the video above)
How to find the last row of data using a Macro/VBA in Exce…
Next Empty Row Trick in Excel VBA & Macros
Tutorial:
A simple way to find the next completely empty row in Excel using VBA/Macros, even if som…
How to Add a New Line to a Message Box (MsgBox) in Excel VBA Macros
Tutorial: I’ll show you how to create a message box popup window in Excel that contains text on mult…
Loop Through an Array in Excel VBA Macros
Tutorial:
I’ll show you how to loop through an array in VBA and macros in Excel. This is a fairly…
Filter Data in Excel to Show Only the Top X Percent of that Data Set — AutoFilter
Macro: This Excel macro filters a set of data in Excel and displays only the top X percent of tha…
Sort Data Left to Right in Excel
Tutorial: How to sort columns of data in Excel. This is the same as sorting left to right.
This wi…
Subscribe for Weekly Tutorials
BONUS: subscribe now to download our Top Tutorials Ebook!
На чтение 3 мин. Просмотров 13 Опубликовано 20.05.2021
На большом листе, если вы хотите быстро и легко определить последнюю строку или столбец, содержащие значения, вы можете просто перетащить полосу прокрутки, чтобы найти ее. Но будет больно, если на вашем листе будут тысячи строк данных. В этой статье я расскажу о некотором полезном коде VBA для решения этой задачи.
Найдите последнюю строку или столбец с данными с помощью кода VBA
Найдите и выберите последнюю строку или столбец с данными с помощью Kutools for Excel
Содержание
- Найти последнюю строку или столбец с данными с помощью кода VBA
- Найти и выберите последнюю строку или столбец с данными с помощью Kutools for Excel
- Найдите и выберите последнюю строку или столбец с данными с помощью Kutools for Excel
Найти последнюю строку или столбец с данными с помощью кода VBA
Большинство из нас может подумать о том, чтобы найти последнюю ячейку, нажав Ctrl + End клавиши, чтобы найти последнюю строку и столбец, но сочетание клавиш не найдет ячейку с точным значением, если некоторые ячейки имеют форматирование ниже диапазона данных. Итак, используйте следующий код VBA:
1 . Активируйте свой рабочий лист, на котором вы хотите определить последнюю строку или столбец с данными.
2 . Удерживая нажатыми клавиши ALT + F11 , откройте окно Microsoft Visual Basic для приложений .
3 . Затем нажмите Insert > Module и вставьте следующий код в окно модуля .
Код VBA: найти последнюю строку с данными
4 . Затем нажмите клавишу F5 , чтобы запустить этот код, и появится окно подсказки, в котором будет указан номер строки используемого диапазона. См. Снимок экрана:
5 . Продолжайте нажимать кнопку OK , на этот раз номер последней строки со значениями был показан, как показано на следующем снимке экрана:
Примечание. Чтобы найти последний столбец с данными, примените этот код:
Код VBA: найти последний столбец с данными
Найти и выберите последнюю строку или столбец с данными с помощью Kutools for Excel
Если вы хотите напрямую найти и выбрать последнюю строку или столбец с данными в Excel, Выбрать последний Строка и утилиты Выбрать последний столбец из Kutools of Excel могут вам помочь. Пожалуйста, сделайте следующее.
Перед применением Kutools for Excel , пожалуйста, сначала загрузите и установите его .
1. Если вы хотите найти и выбрать последнюю строку с данными, нажмите Kutools > Выбрать > Выбрать последнюю ячейку > Последняя строка . См. Снимок экрана:
Примечание : для поиска и выбора последнего столбца с данными нажмите Kutools > Выберите > Выбрать последнюю ячейку > Последний столбец .
Затем последняя строка или столбец с данными на текущем листе найдена и немедленно выбрана.
Если вы хотите получить 30-дневную бесплатную пробную версию этой утилиты, пожалуйста щелкните, чтобы загрузить его , а затем перейдите к применению операции в соответствии с указанными выше шагами.
Найдите и выберите последнюю строку или столбец с данными с помощью Kutools for Excel
Karataev Пользователь Сообщений: 2306 |
да такой способ работает. попробую его использовать. спасибо |
Максим Зеленский Пользователь Сообщений: 4646 Microsoft MVP |
#32 24.11.2014 14:47:56
Выделилось неправильно что? Первая последовательность выделяет все ячейки с константами (не-формулами). Shift-Enter выделит крайнюю правую заполненную в последней строке с константами. F1 творит чудеса |
||
Михаил С. Пользователь Сообщений: 10514 |
#33 24.11.2014 14:52:50
Та, которая ниже. |
||
Karataev Пользователь Сообщений: 2306 |
Максим Зеленский
ваш способ превращает определение последней строки и столбца в ребус- нужно представить,что ниже,что выше. проще сделать макрос. |
Максим Зеленский Пользователь Сообщений: 4646 Microsoft MVP |
#35 24.11.2014 15:22:23
Михаил, так я и пытаюсь у автора топика узнать, кого он ищет как последнюю. И что он будет искать макросом F1 творит чудеса |
||
Karataev Пользователь Сообщений: 2306 |
Максим Зеленский
нужно найти последнюю строку и столбец с данными. это означает,что в ячейке есть какие-нибудь данные. |
Karataev Пользователь Сообщений: 2306 |
Максим Зеленский
по поводу поста 32. на свежую голову посмотрел. оказывается на листе смесь констант и формул,поэтому неправильно выделилось, т.к. формулы не захватились. т.к. одновременно нельзя выделять и константы и формулы,то ваш способ не подходит. остается только Найти и заменить и shift+enter. |
Ну так и предполагалось. Метод Михаила лучше. Но увы, с последним столбцом придется помучиться |
|
Karataev Пользователь Сообщений: 2306 |
метод Михаила не лучше ,а единственный способ без макросов и формул поэтому удобнее,наверное,макрос использовать. Изменено: Karataev — 25.11.2014 09:16:33 |
Karataev Пользователь Сообщений: 2306 |
но у вас решение с помощью формул. формулам для моей задачи не подходит. |
TSN Пользователь Сообщений: 217 |
#42 25.11.2014 09:59:17
Именно так.
|
||||
Karataev Пользователь Сообщений: 2306 |
смысл этой темы -найти решение без vba. поэтому не понимаю,зачем вы это пишите в этой теме . не вижу логики в ваших действиях |
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
#44 25.11.2014 10:03:21
<#0> |
||||
Karataev Пользователь Сообщений: 2306 |
теперь понятно. люди думают,что я не знаю,как узнать последнюю строку и столбец с помощью макроса. в этой теме не нужно писать,как узнать последнюю строку и столбец с помощью макроса. Изменено: Karataev — 25.11.2014 10:06:23 |
Строгий ТС |
|
TSN Пользователь Сообщений: 217 |
#47 25.11.2014 10:07:43
Вот именно Вы определитесь что Вам нужно. Изменено: TSN — 25.11.2014 14:40:34 |
||||||
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
#48 25.11.2014 10:08:55
Про исключение формул в теме ничего нет. <#0> |
||||
Karataev Пользователь Сообщений: 2306 |
в этой теме 47 постов и только один пост содержит нужную информацию. я бы название темы еще изменил -добавил «и без формул» Изменено: Karataev — 25.11.2014 10:10:53 |
vikttur Пользователь Сообщений: 47199 |
#50 25.11.2014 11:00:26 TSN, прошу обращать внимание на свои цитаты. Исправьте, пожалуйста. Karataev , название поменял. Но, так как предложены решения и формулами, и в VBA, убрал «без VBA».
Решение получено? |
||
Karataev Пользователь Сообщений: 2306 |
нет, в excel нет средств для решения этой задачи. нужно использовать макрос. |
Максим Зеленский Пользователь Сообщений: 4646 Microsoft MVP |
#52 25.11.2014 11:20:26
то есть, если на листе заполнено две ячейки, B4 и D2, вы хотите найти столбец D и строку 4? F1 творит чудеса |
||
Karataev Пользователь Сообщений: 2306 |
#53 25.11.2014 11:23:39 Максим Зеленский
приходится много действий делать. проще сделать макрос и одним щелчком узнать всю информацию. |