Last cell in vba excel

Хитрости »

1 Май 2011              403689 просмотров


Очень часто при внесении данных на лист Excel возникает вопрос определения последней заполненной или первой пустой ячейки. Чтобы впоследствии с этой первой пустой ячейки начать заносить данные. В этой теме я опишу несколько способов определения последней заполненной ячейки.

В качестве переменной, которой мы будем присваивать номер последней заполненной строки, у нас во всех примерах будет lLastRow. Объявлять мы её будем как Long. Для экономии памяти можно было бы использовать и тип Integer, но т.к. строк на листе может быть больше 32767(это максимальное допустимое значение переменных типа Integer) нам понадобиться именно Long, во избежание ошибки. Подробнее про типы переменных можно прочитать в статье Что такое переменная и как правильно её объявить

Одинаковые переменные для всех примеров
Во всех примерах ниже мы будем запоминать номер последней строки или столбца в одни и те же переменные:

    Dim lLastRow As Long
    'а для lLastCol можно было бы применить и тип Integer,
    'т.к. столбцов в Excel пока меньше 32767, но для однообразности назначим тоже Long
    Dim lLastCol As Long
  • Определение последней ячейки через свойство End
  • Определение последней ячейки через SpecialCells
  • Определение последней ячейки через UsedRange
  • Определение последней ячейки через метод Find
  • Несколько практических кодов

  • Способ 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.

    1. UsedRange
    2. xlDown
    3. 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.

    enter image description here

    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
    

    To find the last row, column, or cell you can use the range’s “End” property. The end property allows you to navigate to the end of the data range (to the last cell that is not empty). With this, there are constants that you can use to decide in which direction you want to navigate (top, bottom, left, or right).

    1. Define the cell or the range from where you want to navigate to the last row.
    2. After that, enter a dot to get the list of properties and methods.
    3. Select or type “End” and enter a starting parenthese.
    4. Use the argument that you want to use.
    5. Further, use the address property to get the address of the cell.
    MsgBox Range("A1").End(xlDown).Address

    When you run the above code, it shows you a message box with the row number of the last non-empty cell.

    Find the Last Column using VBA

    Now, let’s say you want to find the last column. In that case, instead of using “xlDown” constant, you need to use the “xlRight”, and if you want to select that cell instead of having the address then you can use the “select” method. Consider the following method.

    Range("A1").End(xlToRight).Select

    Find the Last Cell

    By using the same method, you can also get the last cell which is a non-empty cell. To write this code, you need to know the last row and column.

    Sub vba_last_row()
    
      Dim lRow As Long
      Dim lColumn As Long
    
      lRow = Range("A1").End(xlDown).Row
      lColumn = Range("A1").End(xlToRight).Column
    
      Cells(lRow, lColumn).Select
    
    End Sub

    To understand the above code, we need to split it into three parts.

    1. In the FIRST part, you have declared two variables to store the row and the column number.
    2. In the SECOND part, you have used “End” with the “xlDown” and then the Row property to get the row number of the last, and in the same way, you have used the “End” with the “xlToRight” and then the “Column” property to get the column number of the last column.
    3. In the THIRD part, by using the last column number and last row number refer to the last cell and select it.

    Note: If you want to select a cell in the different worksheets using the last row and last column method, you need to have that worksheet activated first.

    Last Row, Column, and Cell using the Find Method

    You can also use the find method with the range object to get the worksheet’s last row, column, and cell. To know the row number, here is the code:

    Sub vba_last_row()
    
    Dim iRow As Long
    
    iRow = Cells.Find(What:="*", _
                        After:=Range("A1"), _
                        LookAt:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row
    
    MsgBox iRow
    
    End Sub

    For column number:

    Sub vba_last_row()
    
    Dim iColumn As Long
    
    iColumn = Cells.Find(What:="*", _
                        After:=Range("A1"), _
                        LookAt:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Column
    
    MsgBox iColumn
    
    End Sub

    To get the cell address of the last cell.

    Sub vba_last_row()
    
    Dim iColumn As Long
    Dim iRow As Long
    
    iColumn = Cells.Find(What:="*", _
                        After:=Range("A1"), _
                        LookAt:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByColumns, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Column                  
    
    iRow = Cells.Find(What:="*", _
                        After:=Range("A1"), _
                        LookAt:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row                   
    
    Cells(iRow, iColumn).Address
    
    End Sub

    More Tutorials

      • Count Rows using VBA in Excel
      • Excel VBA Font (Color, Size, Type, and Bold)
      • Excel VBA Hide and Unhide a Column or a Row
      • Excel VBA Range – Working with Range and Cells in VBA
      • Apply Borders on a Cell using VBA in Excel
      • Insert a Row using VBA in Excel
      • Merge Cells in Excel using a VBA Code
      • Select a Range/Cell using VBA in Excel
      • SELECT ALL the Cells in a Worksheet using a VBA Code
      • ActiveCell in VBA in Excel
      • Special Cells Method in VBA in Excel
      • UsedRange Property in VBA in Excel
      • VBA AutoFit (Rows, Column, or the Entire Worksheet)
      • VBA ClearContents (from a Cell, Range, or Entire Worksheet)
      • VBA Copy Range to Another Sheet + Workbook
      • VBA Enter Value in a Cell (Set, Get and Change)
      • VBA Insert Column (Single and Multiple)
      • VBA Named Range | (Static + from Selection + Dynamic)
      • VBA Range Offset
      • VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
      • VBA Wrap Text (Cell, Range, and Entire Worksheet)
      • VBA Check IF a Cell is Empty + Multiple Cells

      ⇠ Back to What is VBA in Excel

      Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes

      Today I am going to take on one of the most frequent question people ask about Excel VBA – how to the the last row, column or cell of a spreadsheet using VBA. The Worksheet range used by Excel is not often the same as the Excel last row and column with values. Therefore I will be careful to explain the differences and nuisances in our quest to find the last row, column or cell in and Excel spreadsheet.

      In this post I am covering the following types of Excel VBA Ranges:

      See below sections for details.

      The Last Row may as be interpreted as:

      • Last Row in a Column
      • Last Row with Data in Worksheet
      • Last Row in Worksheet UsedRange

      Last Row in a Column

      vba last row

      To get the Last Row with data in a Column we need to use the End property of an Excel VBA Range.

      Dim lastRow as Range
      
      'Get Last Row with Data in Column
      Debug.Print Range("A1").End(xlDown).Row 'Result: 5
      Set lastRow = Range("A1").End(xlDown).EntireRow
      
      'Get Last Cell with Data in Row
      Dim lastRow as Range
      Set lastRow = Range("A1").End(xlDown)
      

      Last Row with Data in Worksheet

      vba last used row

      To get the Last Row with data in a Worksheet we need to use the SpecialCells or Find properties of an Excel VBA Range.

      Dim lastRow as Range, ws As Worksheet
      Set ws = ActiveSheet
      
      'Get Last Row with Data in Worksheet using SpecialCells
      Debug.Print ws.Cells.SpecialCells(xlCellTypeLastCell).Row
      Set lastRow = ws.Cells.SpecialCells(xlCellTypeLastCell).EntireRow 
      
      'Get Last Row with Data in Worksheet using Find
      Debug.Print Debug.Print ws.Cells.Find(What:="*", _
              After:=ws.Cells(1), _
              Lookat:=xlPart, _
              LookIn:=xlFormulas, _
              SearchOrder:=xlByRows, _
              SearchDirection:=xlPrevious, _
              MatchCase:=False).Row
      Set lastRow = Debug.Print ws.Cells.Find(What:="*", _
              After:=ws.Cells(1), _
              Lookat:=xlPart, _
              LookIn:=xlFormulas, _
              SearchOrder:=xlByRows, _
              SearchDirection:=xlPrevious, _
              MatchCase:=False).EntireRow
      

      Last Row in Worksheet UsedRange

      vba last used row usedrange

      To get the Last Row in the Worksheet UsedRange we need to use the UsedRange property of an VBA Worksheet.

      'Get Last Row in Worksheet UsedRange
      Dim lastRow as Range, ws As Worksheet
      Set ws = ActiveSheet
      Debug.Print ws.UsedRange.Rows(ws.UsedRange.Rows.Count).Row
      Set lastRow = ws.UsedRange.Rows(ws.UsedRange.Rows.Count).EntireRow
      

      The UsedRange represents a Range used by an Excel Worksheet. The Used Range starts at the first used cell and ends with the most right, down cell that is used by Excel. This last cell does not need to have any values or formulas as long as it was edited or formatted in any point in time

      VBA Last Column

      The Last Column may as be interpreted as:

      • Last Column with Data in a Row
      • Last Column with Data in Worksheet
      • Last Column in Worksheet UsedRange

      Last Column with Data in a Row

      vba last used column

      Last Column with Data in a Worksheet

      To get the Last Column with data in a Worksheet we need to use the SpecialCells or Find properties of an Excel VBA Range.

      Dim lastColumn as Range, ws As Worksheet
      Set ws = ActiveSheet
      
      'Get Last Column with Data in Worksheet using SpecialCells
      Debug.Print ws.Cells.SpecialCells(xlCellTypeLastCell).Column
      Set lastColumn = ws.Cells.SpecialCells(xlCellTypeLastCell).EntireColumn 
      
      'Get Last Column with Data in Worksheet using Find
      Debug.Print Debug.Print ws.Cells.Find(What:="*", _
              After:=ws.Cells(1), _
              Lookat:=xlPart, _
              LookIn:=xlFormulas, _
              SearchOrder:=xlByRows, _
              SearchDirection:=xlPrevious, _
              MatchCase:=False).Column
      Set lastColumn = Debug.Print ws.Cells.Find(What:="*", _
              After:=ws.Cells(1), _
              Lookat:=xlPart, _
              LookIn:=xlFormulas, _
              SearchOrder:=xlByRows, _
              SearchDirection:=xlPrevious, _
              MatchCase:=False).EntireColumn
      

      Last Column in Worksheet UsedRange

      vba last used column usedrange

      To get the Last Column in the Worksheet UsedRange we need to use the UsedRange property of an VBA Worksheet.

      'Get Last Column in Worksheet UsedRange
      Dim lastColumn as Range, ws As Worksheet
      Set ws = ActiveSheet
      Debug.Print ws.UsedRange.Columns(ws.UsedRange.Columns.Count).Column
      Set lastColumn = ws.UsedRange.Columns(ws.UsedRange.Columns.Count).EntireColumn
      

      VBA Last Cell

      The Last Cell may as be interpreted as:

      • Last Cell in a series of data
      • Last Cell with Data in Worksheet
      • Last Cell in Worksheet UsedRange

      Last Cell in a series of data

      vba last cell in data series

      To get the Last Cell in a series of data (table with non-blank values) we need to use the End property of an Excel VBA Range.

      Dim lastCell as Range
      
      'Get Last Cell in a series of data
      Dim lastCell as Range
      Set lastCell = Range("A1").End(xlRight).End(xlDown)
      Debug.Print "Row: " & lastCell.row & ", Column: " & lastCell.column
      

      Last Cells with Data in Worksheet

      vba last cell in worksheet

      To get the Last Cell with data in a Worksheet we need to use the SpecialCells or Find properties of an Excel VBA Range.

      Dim lastCell as Range, ws As Worksheet
      Set ws = ActiveSheet
      
      'Get Last Cell with Data in Worksheet using SpecialCells
      Set lastCell = ws.Cells.SpecialCells(xlCellTypeLastCell)
      Debug.Print "Row: " & lastCell.row & ", Column: " & lastCell.column
      
      'Get Last Cell with Data in Worksheet using Find
      Set lastColumn = Debug.Print ws.Cells.Find(What:="*", _
              After:=ws.Cells(1), _
              Lookat:=xlPart, _
              LookIn:=xlFormulas, _
              SearchOrder:=xlByRows, _
              SearchDirection:=xlPrevious, _
              MatchCase:=False)
      Debug.Print "Row: " & lastCell.row & ", Column: " & lastCell.column
      

      Last Cell in Worksheet UsedRange

      vba last cell in usedrange

      To get the Last Cell in the Worksheet UsedRange we need to use the UsedRange property of an VBA Worksheet.

      'Get Last Cell in Worksheet UsedRange
      Dim lastCell as Range, ws As Worksheet
      Set ws = ActiveSheet
      
      Set lastCell = ws.UsedRange.Cells(ws.UsedRange.Rows.Count,ws.UsedRange.Columns.Count)
      Debug.Print "Row: " & lastCell.row & ", Column: " & lastCell.column
      

      VBA UsedRange

      vba usedrange

      The VBA UsedRange represents the area reserved and saved by Excel as the currently used Range on and Excel Worksheet. The UsedRange constantly expands the moment you modify in any way a cell outside of the previously Used Range of your Worksheet.

      The UsedRange is not reduced if you Clear the Contents of Range. The only way to reduce a UsedRange is to delete the unused rows and columns.

      How to check the UsedRange

      The easiest way to check the currently UsedRange in an Excel Worksheet is to select a cell (best A1) and hitting the following key combination: CTRL+SHIFT+END. The highlighted Range starts at the cell you selected and ends with the last cell in the current UsedRange.

      Check UsedRange in VBA

      Use the code below to check the area of the UsedRange in VBA:

      Dim lastCell As Range, firstCell As Range, ws As Worksheet
      Set ws = ActiveSheet
          
      Set lastCell = ws.UsedRange.Cells(ws.UsedRange.Rows.Count, ws.UsedRange.Columns.Count)
      Set firstCell = ws.UsedRange.Cells(1, 1)
      Debug.Print "First Cell in UsedRange. Row: " & firstCell.Row & ", Column: " & firstCell.Column
      Debug.Print "Last Cell in UsedRange. Row: " & lastCell.Row & ", Column: " & lastCell.Column    
      

      For the screen above the result will be:

      First Cell in UsedRange; Row: 2, Column: 2
      Last Cell in UsedRange; Row: 5, Column: 6
      

      First UsedCell in UsedRange

      The below will return get the first cell of the VBA UsedRange and print its row and column:

      Dim firstCell as Range
      Set firstCell = ws.UsedRange.Cells(1, 1)
      Debug.Print "First Cell in UsedRange. Row: " & firstCell.Row & ", Column: " & firstCell.Column
      

      Last UsedCell in UsedRange

      The below will return get the first cell of the VBA UsedRange and print its row and column:

      Dim lastCell as Range
      Set lastCell = ws.UsedRange.Cells(ws.UsedRange.Rows.Count, ws.UsedRange.Columns.Count)
      Debug.Print "Last Cell in UsedRange; Row: " & lastCell.Row & ", Column: " & lastCell.Column
      

      Different Ways to Find The Last Row or Last Column Using VBA In Microsoft Excel

      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 Poorly-Formatted Data Set

      An Example of a Well-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

      ThreeWave
      Finding The Last Used Cell In A Range

      This page describes how to find the last used cell in a range.
      ShortFadeBar

      It is quite simple to get the last used in a single row or column. You do this by
      emulating the behavior of the END key and one of the arrow keys. For
      example, to get the last used cell in column C on Sheet1, use code like

      Dim WS As Worksheet
      Dim LastCell As Range
      Dim LastCellRowNumber As Long
      
      Set WS = Worksheets("Sheet1")
      With WS
          Set LastCell = .Cells(.Rows.Count, "C").End(xlUp)
          LastCellRowNumber = LastCell.Row
      End With
      

      This works by going to the last row of the worksheet in column C and then uses End to
      scan upwards until a non-blank cell is encountered. There may well be empty cells above this cell, but this
      is the last used cell in the column. The Range variable LastCell
      references the last cell. The Long variable LastCellRowNumber contains
      the row number of the last cell in the column.

      You can use a formula to return the row number of the last non-blank cell. In this case, the last used
      cell is one that contains anything that is not an empty string. If a formula returns an empty string, that is ignored.

      =MAX(ROW(A1:A100)*(A1:A100<>»»))

      Change the instances of 100 to a row that is after any possible data.
      This is an array formula, so you must press CTRL SHIFT ENTER rather than
      just ENTER when you first enter the formula and whenever you edit it later.

      The code for finding the last used cell in a row is nearly identical.

      Dim WS As Worksheet
      Dim LastCell As Range
      Dim LastCellColumnNumber As Long
      Dim RowNumber As Long
      Set WS = Worksheets("Sheet1")
      With WS
          RowNumber = 2
          If .Cells(RowNumber, .Columns.Count) <> vbNullString Then
              Set LastCell = .Cells(RowNumber, .Columns.Count)
              LastCellColumnNumber = LastCell.Column
          Else
              Set LastCell = .Cells(RowNumber, .Columns.Count).End(xlToLeft)
              LastCellColumnNumber = LastCell.Column
          End If
      End With
      

      where RowNum is the row number to test. You can use an array formula to get the last
      used column in a row:

      =MAX(COLUMN(A:IV)*(A1:IV1<>»»))

      In both of the VBA code snippets, the last cell may appear to be blank if it contains a formula that
      evaluates to an empty string. The formulas treat a cell that contains a formula that returns an empty
      string to be empty, so the last used cell may be above or to the left of a cell with such a formula.

      In order to get the last cell in a range, you first need to think about what constitutes
      the «last cell». If you search row-by-row, moving across one row then down to the next,
      the last cell is the right-most cell in the last row than contains any values. If you search
      column-by-column, moving down one column then moving across to the next, the last cell is the lower-most
      cell in the last column that contains a non-empty element. For example,in the following range
      of cells:
      Last Cell Image
      the value g is the last entry when searching on a row-by-row basis. On the other hand, the
      value e is the last entry when searching column-by-column. Which is the «true» last cell
      depends on the context of the data.

      The VBA code SpecialCells(xlCellTypeLastCell) scans row by row to find the last cell, so in the
      table above, the cell containing the value g would be returned as the last cell. There is no way to change the
      way that SpecialCells(xlCellTypeLastCell) determines the last cell.

      With some VBA, we can find the last cell on either a row basis or a column basis. The code below
      works by calling the Find method on the specified range, with settings to search for
      any non-blank content (the * in the what parameter), and
      scanning from the end of the range backwards to the start of the range (the xlPrevious
      value of the SearchDirection parameter).

      The GetLastCell procedure is used to find the last cell and has the
      declaration:

      Public Function GetLastCell(InRange As Range, SearchOrder As XlSearchOrder, _
                              Optional ProhibitEmptyFormula As Boolean = False) As Range
      

      The InRange is the range of which the last cell should be found. The
      SearchOrder parameter is either xlByColumns or
      xlByRows. If SearchOrder is any value other than
      xlByRows, xlByColumns, or
      xlByRows + xlByColumns (see below), the code raises an error 5 (Invalid procedure call or argument).
      The ProhibitEmptyFormula indicates how the
      code should treat a cell that contains a formula that evaluates to an empty string. If this parameter is
      omitted or False, the last cell is allowed to be a cell containing a formula that evaluates to an empty
      string. If this value is True, then the last cell must be a cell containing a static constant or
      a formula that does not evaluate to an empty string.

      The SearchOrder can also take the value xlByColumns +
      xlByColumns
      which makes the last cell the intersection of the row containing the
      last cell on a row-by-row basis and the column of the column containing the last cell on a column-by-column
      basis. This cell may be empty. In the example above, this cell is the cell immediately below the value
      e.

      If you want the absolute last cell of a range, regardless of whether it has any content, you can use
      the simple code:

          Dim RR As Range
          Dim LastCell As Range
          Set RR = Range("A1:C10")
          Set LastCell = RR(RR.Cells.Count)
      

      SectionBreak

      The complete code for GetLastCell is shown below:

      Public Function GetLastCell(InRange As Range, SearchOrder As XlSearchOrder, _
                              Optional ProhibitEmptyFormula As Boolean = False) As Range
      
      Dim WS As Worksheet
      Dim R As Range
      Dim LastCell As Range
      Dim LastR As Range
      Dim LastC As Range
      Dim SearchRange As Range
      Dim LookIn As XlFindLookIn
      Dim RR As Range
      
      Set WS = InRange.Worksheet
      
      If ProhibitEmptyFormula = False Then
          LookIn = xlFormulas
      Else
          LookIn = xlValues
      End If
      
      Select Case SearchOrder
          Case XlSearchOrder.xlByColumns, XlSearchOrder.xlByRows, _
                  XlSearchOrder.xlByColumns + XlSearchOrder.xlByRows
              
          Case Else
              Err.Raise 5
              Exit Function
      End Select
      
      With WS
          If InRange.Cells.Count = 1 Then
              Set RR = .UsedRange
          Else
             Set RR = InRange
          End If
          Set R = RR(RR.Cells.Count)
          
          If SearchOrder = xlByColumns Then
              Set LastCell = RR.Find(what:="*", after:=R, LookIn:=LookIn, _
                      LookAt:=xlPart, SearchOrder:=xlByColumns, _
                      SearchDirection:=xlPrevious, MatchCase:=False)
          ElseIf SearchOrder = xlByRows Then
              Set LastCell = RR.Find(what:="*", after:=R, LookIn:=LookIn, _
                      LookAt:=xlPart, SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, MatchCase:=False)
          ElseIf SearchOrder = xlByColumns + xlByRows Then
              Set LastC = RR.Find(what:="*", after:=R, LookIn:=LookIn, _
                      LookAt:=xlPart, SearchOrder:=xlByColumns, _
                      SearchDirection:=xlPrevious, MatchCase:=False)
              Set LastR = RR.Find(what:="*", after:=R, LookIn:=LookIn, _
                      LookAt:=xlPart, SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, MatchCase:=False)
              Set LastCell = Application.Intersect(LastR.EntireRow, LastC.EntireColumn)
          Else
              Err.Raise 5
              Exit Function
          End If
      End With
      
      Set GetLastCell = LastCell
      
      End Function
      '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
      ' END CODE GetLastCell
      '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
      

      ShortFadeBar

      LastUpdate This page last updated: 20-August-2008.

      На чтение 10 мин. Просмотров 47.6k.

      Итог: узнаете, как найти последнюю строку, столбец или ячейку в таблице с использованием трех различных методов на VBA. Используемый метод зависит от макета данных и от того, содержит ли лист пустые ячейки.

      Уровень мастерства: средний

      3 способа найти последнюю заполненную ячейку 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

      Последнее значение в столбце Excel

      Метод Range.Find — я предпочитаю этот способ, чтобы найти последнюю строку, столбец или ячейку. Он самый универсальный, но и самый страшный.

      Последнее значение в столбце Excel

      У Range.Find много аргументов, но пусть это вас не пугает. Когда вы знаете, что они делают, вы можете использовать Range.Find для многих вещей в VBA.

      Range.Find — это в основном способ программирования меню «Find» в Excel. Он делает то же самое, и большинство аргументов Range.Find являются опциями в меню Find.

      Последнее значение в столбце Excel

      Пример кода 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) и проходит по каждой строке, пока не
      найдет непустую ячейку. При обнаружении непустого он останавливается и
      возвращает номер строки.

      Range.Find VBA Excel

      Вот подробное объяснение каждого аргумента.

      • 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 — все еще мой любимый метод для нахождения последней ячейки из-за ее универсальности. Но нужно много напечатать и запомнить. К счастью, вам это не нужно.

      Вы можете использовать макро рекордер, чтобы быстро создать код со всеми аргументами.

      1. Запустить макро рекордер
      2. Нажмите Ctrl + F
      3. Затем нажмите кнопку «Найти далее»

      Код для метода 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 возникает вопрос определения последней заполненной или первой пустой ячейки. Чтобы впоследствии с этой первой пустой ячейки начать заносить данные. В этой теме я опишу несколько способов определения последней заполненной ячейки.

      В качестве переменной, которой мы будем присваивать номер последней заполненной строки, у нас во всех примерах будет lLastRow. Объявлять мы её будем как Long. Для экономии памяти можно было бы использовать и тип Integer, но т.к. строк на листе может быть больше 32767(это максимальное допустимое значение переменных типа Integer) нам понадобиться именно Long, во избежание ошибки. Подробнее про типы переменных можно прочитать в статье Что такое переменная и как правильно её объявить

      Одинаковые переменные для всех примеров

      Dim lLastRow As Long ‘а для lLastCol можно применить тип Integer, ‘т.к. столбцов в Excel пока меньше 32767 Dim lLastCol As Long

      1

      2

      3

      4

          Dim lLastRow As Long

          ‘а для lLastCol можно применить тип Integer,

          ‘т.к. столбцов в Excel пока меньше 32767

          Dim lLastCol As Long


      Способ 1:
      Определение последней заполненной строки через свойство End

      lLastRow = Cells(Rows.Count,1).End(xlUp).Row

      1

          lLastRow = Cells(Rows.Count,1).End(xlUp).Row

      определяя таким способом нам надо знать что:
      1 — это номер столбца, последнюю заполненную ячейку в котором мы определяем. В данном случае это столбце №1 или А.
      Это самый распространенный метод определения последней строки. Используя его мы можем определить последнюю ячейку только в одном конкретном столбце. Но в большинстве случаев этого достаточно.

      Правда, следует знать одну вещь: если у вас заполнены все строки в просматриваемом столбце(или будет заполнена самая последняя ячейка столбца) — то результат будет неверный(ну или не совсем такой, какой ожидали увидеть вы)
      Определение последнего столбца через свойство End

      lLastCol = Cells(1, Columns.Count).End(xlToLeft).Column

      1

          lLastCol = Cells(1, Columns.Count).End(xlToLeft).Column

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

      Данный метод лишен недостатков, присущих второму и третьему способам. Однако есть другой, в определенных ситуациях даже полезный: при таком методе определения игнорируются строки, скрытые фильтром, группировкой или командой Скрыть (Hide). Т.е. если последняя строка таблицы будет скрыта, то данный метод вернет номер последней видимой заполненной строки, а не последней реально заполненной.


      Способ 2:
      Определение последней заполненной строки через SpecialCells

      lLastRow = Cells.SpecialCells(xlLastCell).Row

      1

          lLastRow = Cells.SpecialCells(xlLastCell).Row

      Определение последнего столбца через SpecialCells

      lLastCol = Cells.SpecialCells(xlLastCell).Column

      1

          lLastCol = Cells.SpecialCells(xlLastCell).Column

      Данный метод не требует указания номера столбца и возвращает максимальную последнюю ячейку(строку — Row либо столбец — Column). Но используя данный метод следует помнить, что не всегда можно получить реальную последнюю заполненную ячейку, т.е. именно ячейку со значением. Если вы где-то ниже занесете данные и сразу удалите их из таблицы, а затем примените такой метод, то lLastRow будет равна значению строки, из которой вы только что удалили значения. Другими словами требует обязательного обновления данных, а этого можно добиться только сохранив и закрыв документ и открыв его снова. Так же, если какая-либо ячейка содержит форматирование(например, заливку), но не содержит никаких значений, то она тоже будет считаться заполненной.
      Плюс данный метод определения последней ячейки не будет работать на защищенном листе(Рецензирование -Защитить лист).

      Я этот метод использую только для определения в только что созданном документе, в котором только добавляю строки.


      Способ 3:
      Определение последней строки через UsedRange

      lLastRow = ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count — 1

      1

          lLastRow = ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count — 1

      Определение последнего столбца через UsedRange

      lLastCol = ActiveSheet.UsedRange.Column + ActiveSheet.UsedRange.Columns.Count — 1

      1

          lLastCol = ActiveSheet.UsedRange.Column + ActiveSheet.UsedRange.Columns.Count — 1

      НЕМНОГО ПОЯСНЕНИЙ:

      • ActiveSheet.UsedRange.Row — этой строкой мы определяем первую ячейку, с которой начинаются данные на листе. Важно понимать для чего это — если у вас первые строк 5 не заполнены ничем, то данная строка вернет 6(т.е. номер первой строки с данными). Если же все строки заполнены — то вернет 1.
      • ActiveSheet.UsedRange.Rows.Count — определяем кол-во строк, входящих в весь диапазон данных на листе.
        Т.е. получается: первая строка данных + кол-во строк с данными — 1. Зачем вычитать единицу? Попробуем посчитать вместе: первая строка: 3. Всего строк: 3. 3 + 3 = 6. Вроде все верно, чего тут непонятного? А теперь выделите на листе три ячейки, начиная с 3-ей. Все верно. Ведь у нас в 3-ей строке уже есть данные. Думаю, остальное уже понятно и без моих пояснений.
      • То же самое и с ActiveSheet.UsedRange.Column, только уже не для строк, а для столбцов.

      Обладает всеми недостатками предыдущего метода.. Однако, можно перед определением последней строки/столбца записать строку: With ActiveSheet.UsedRange: End With
      Это должно переопределить границы рабочего диапазона и тогда определение последней строки/столбца сработает как ожидается, даже если до этого в ячейке содержались данные, которые впоследствии были удалены.

      Если хотите получить первую пустую ячейку на листе придется вспомнить математику. Т.к. последнюю заполненную мы определили, то первая пустая — следующая за ней. Т.е. к результату необходимо прибавить 1.


      Способ 4:
      Определение последней строки и столбца, а так же адрес ячейки методом Find

      Dim rF As Range Dim lLastRow As Long, lLastCol As Long ‘ищем последнюю ячейку на листе, в которой хранится хоть какое-то значение Set rF = ActiveSheet.UsedRange.Find(«*», , xlValues, xlWhole, xlPrevious) If Not rF Is Nothing Then lLastRow = rF.Row ‘последняя заполненная строка lLastCol = rF.Column ‘последний заполненный столбец MsgBox rF.Address ‘показываем сообщение с адресом последней ячейки Else ‘если ничего не нашлось — значит лист пустой ‘и можно назначить в качестве последних первую строку и столбец lLastRow = 1 lLastCol = 1 End If

      Dim rF As Range

          Dim lLastRow As Long, lLastCol As Long

          ‘ищем последнюю ячейку на листе, в которой хранится хоть какое-то значение

          Set rF = ActiveSheet.UsedRange.Find(«*», , xlValues, xlWhole, xlPrevious)

          If Not rF Is Nothing Then

              lLastRow = rF.Row    ‘последняя заполненная строка

              lLastCol = rF.Column ‘последний заполненный столбец

              MsgBox rF.Address ‘показываем сообщение с адресом последней ячейки

          Else

              ‘если ничего не нашлось — значит лист пустой

              ‘и можно назначить в качестве последних первую строку и столбец

              lLastRow = 1

              lLastCol = 1

          End If

      Этот метод, пожалуй, самый оптимальный в случае, если надо определить последнюю строку/столбец на листе без учета форматов и формул — только по отображаемому значению в ячейке. Например, если на листе большая таблица и последние строки заполнены формулами, возвращающими пустую ячейку(=»»), предыдущие варианты вернут строку/столбец ячейки с последней формулой, в то время как данный метод вернет адрес ячейки только в случае, если в ячейке реально отображается какое-то значение. Такой подход часто используется для того, чтобы определить границы данных для последующего анализа заполненных данных, чтобы не захватывать пустые ячейки и не тратить время на их проверку.

      Однако данный метод не будет учитывать в просмотре скрытые строки и столбцы. Это следует учитывать при его применении.


      небольшой практический код, который поможет вам понять, как использовать полученную переменную:

      Sub Get_Last_Cell() 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

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      Sub Get_Last_Cell()

          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 Copy_To_Last_Cell() Range(«A1:C» & Cells(Rows.Count, 1).End(xlUp).Row).Select End Sub

      1

      2

      3

      Sub Copy_To_Last_Cell()

          Range(«A1:C» & Cells(Rows.Count, 1).End(xlUp).Row).Select

      End Sub

      А вот такой код скопирует ячейку B1 в первую пустую ячейку столбца A этого же листа:

      Sub Copy_To_Last_Cell() Range(«B1»).Copy Cells(Rows.Count, 1).End(xlUp).Offset(1) End Sub

      1

      2

      3

      Sub Copy_To_Last_Cell()

          Range(«B1»).Copy Cells(Rows.Count, 1).End(xlUp).Offset(1)

      End Sub

      Важно знать: необходимо помнить, что если ячейка содержит формулу, пусть и возвращающую значение «», Excel не считает её пустой(к слову совершенно справедливо) и включает в просмотр при поиске последней ячейки.

      Понравилась статья? Поделить с друзьями:
    • Laser meaning of word
    • Largest word in words with friends
    • Largest word in the english vocabulary
    • Latin word for how are you
    • Largest continent in the word