Vba excel cells rows count 1 end xlup row

Хитрости »

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


Очень часто при внесении данных на лист 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
    ссылки
    статистика

    I was just wondering if you could help me better understand what .Cells(.Rows.Count,"A").End(xlUp).row does. I understand the portion before the .End part.

    Community's user avatar

    asked Nov 21, 2014 at 16:20

    rmdlp's user avatar

    2

    It is used to find the how many rows contain data in a worksheet that contains data in the column «A». The full usage is

     lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row
    

    Where ws is a Worksheet object. In the questions example it was implied that the statement was inside a With block

    With ws
        lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
    End With
    
    1. ws.Rows.Count returns the total count of rows in the worksheet (1048576 in Excel 2010).
    2. .Cells(.Rows.Count, "A") returns the bottom most cell in column «A» in the worksheet

    Then there is the End method. The documentation is ambiguous as to what it does.

    Returns a Range object that represents the cell at the end of the region that contains the source range

    Particularly it doesn’t define what a «region» is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don’t use it like that:

    • If the range is multiple cells, it will use the region of rng.cells(1,1).
    • If the range isn’t in a region, or the range is already at the end of the region, then it will travel along the direction until it enters a region and return the first encountered cell in that region.
    • If it encounters the edge of the worksheet it will return the cell on the edge of that worksheet.

    So Range.End is not a trivial function.

    1. .row returns the row index of that cell.

    answered Nov 21, 2014 at 16:51

    cheezsteak's user avatar

    cheezsteakcheezsteak

    2,6924 gold badges22 silver badges38 bronze badges

    0

    [A1].End(xlUp)
    [A1].End(xlDown)
    [A1].End(xlToLeft)
    [A1].End(xlToRight)
    

    is the VBA equivalent of being in Cell A1 and pressing Ctrl + Any arrow key. It will continue to travel in that direction until it hits the last cell of data, or if you use this command to move from a cell that is the last cell of data it will travel until it hits the next cell containing data.

    If you wanted to find that last «used» cell in Column A, you could go to A65536 (for example, in an XL93-97 workbook) and press Ctrl + Up to «snap» to the last used cell. Or in VBA you would write:

    Range("A65536").End(xlUp) which again can be re-written as Range("A" & Rows.Count).End(xlUp) for compatibility reasons across workbooks with different numbers of rows.

    answered Nov 21, 2014 at 18:13

    SierraOscar's user avatar

    SierraOscarSierraOscar

    17.5k6 gold badges41 silver badges68 bronze badges

    The first part:

    .Cells(.Rows.Count,"A")
    

    Sends you to the bottom row of column A, which you knew already.

    The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:

    Sheet1.Cells(4,"C").End(xlToRight).Select
    

    The program will select E4, the rightmost cell with text in it.

    In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?

    answered Nov 21, 2014 at 16:44

    rpalo's user avatar

    rpalorpalo

    2431 silver badge13 bronze badges

    .Cells(.Rows.Count,"A").End(xlUp).row
    

    I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:

    .Cells(Rows.Count,"A").End(xlUp).row
    

    Before the Cells, you can write your worksheet name, for example:

    Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row
    

    The worksheet name is not necessary when you operate on the same worksheet.

    Jason D's user avatar

    Jason D

    7,84510 gold badges35 silver badges39 bronze badges

    answered Sep 13, 2015 at 18:24

    user5331486's user avatar

    0

     

    zotov

    Пользователь

    Сообщений: 57
    Регистрация: 23.07.2014

    #1

    28.08.2014 02:09:55

    Доброй ночи.Пытаюсь найти диапазон, получается только так:

    Код
    Range("A2:BO" & Cells(Rows.Count, 1).End(xlUp).Row)
     

    Пожалуйста, помогите прикрутить определение адреса последнего столбца:

    Код
    Range(Cells(1, 2), Cells(2, Columns.Count).End(xlToLeft).Column & Cells(Rows.Count, 1).End(xlUp).Row)
     
     

    ikki

    Пользователь

    Сообщений: 9709
    Регистрация: 22.12.2012

    #2

    28.08.2014 02:36:49

    ваше Cells(1, 2) — это не ячейка A2, это B1
    если искать последний столбец по второй строке, а последнюю строку — по первому столбцу, то как-то так:

    Код
    range([a2], cells(cells(rows.count,1).end(xlup).row, cells(2,columns.count).end(xltoleft).column))

    фрилансер Excel, VBA — контакты в профиле
    «Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

     

    zotov

    Пользователь

    Сообщений: 57
    Регистрация: 23.07.2014

    ikki, Спасибо. Действительно,  нужно искать последний столбец по второй строке, а последнюю строку — по первому столбцу. Ваша строка у меня не приживается, не знаю почему. Вроде бы правильная

     

    ikki

    Пользователь

    Сообщений: 9709
    Регистрация: 22.12.2012

    #4

    28.08.2014 03:00:22

    в вашей строке не оговорено, к какому листу какого файла применяются все эти range, cells и columns
    в таком случае — всё выполняется на активном листе.
    возможно, в нужный момент активен другой лист?

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

    Код
    set r = range(...)
    range(...).select
    range(...).copy
    a = range(...).value

    я подумал, что вы об этом знаете.

    Изменено: ikki28.08.2014 03:06:36

    фрилансер Excel, VBA — контакты в профиле
    «Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

     

    zotov

    Пользователь

    Сообщений: 57
    Регистрация: 23.07.2014

    ikki,  Workbooks(«Книга1.xls»).Worksheets(«Лист1»).Range(«A2:BO5000»).Copy (Worksheets(«Данные»).Range(«D1»))

     

    ikki

    Пользователь

    Сообщений: 9709
    Регистрация: 22.12.2012

    #6

    28.08.2014 03:13:15

    скобки вокруг второго диапазона уберите.

    Код
    r1.copy r2

    фрилансер Excel, VBA — контакты в профиле
    «Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

     

    zotov

    Пользователь

    Сообщений: 57
    Регистрация: 23.07.2014

    #7

    28.08.2014 03:35:21

    ikki, Что-то я совсем запутался…

    Цитата
    ikki пишет: я подумал, что вы об этом знаете

    В основном действую методом тыка
    r1.copy r2 — это о чем? и что такое «второй диапазон»?

    Изменено: zotov28.08.2014 23:50:49

     

    ikki

    Пользователь

    Сообщений: 9709
    Регистрация: 22.12.2012

    может, книжку какую уже пора пролистать?
    Workbooks(«Книга1.xls»).Worksheets(«Лист1»).Range(«A2:BO5000»).Copy (Worksheets(«Данные»).Range(«D1»))
    здесь у вас два диапазона: первый — тот, который копируете:
    Workbooks(«Книга1.xls»).Worksheets(«Лист1»).Range(«A2:BO5000»)
    второй — куда копируете:
    Worksheets(«Данные»).Range(«D1»)

    вот этот второй в скобки брать не надо. то есть так:
    Workbooks(«Книга1.xls»).Worksheets(«Лист1»).Range(«A2:BO5000»).Copy Worksheets(«Данные»).Range(«D1»)

    фрилансер Excel, VBA — контакты в профиле
    «Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

     

    zotov

    Пользователь

    Сообщений: 57
    Регистрация: 23.07.2014

    ikki, Нет. Я должен выдавать результаты в совершено другой области. Книжки по программированию каждый день нужно перелистывать тем программистам, которые вынуждают допиливать их «суперпродукты».
    Скобки убрал. Но все-таки интересует «первый диапазон». Может быть метод не подходящий?

    Изменено: zotov28.08.2014 05:22:28

     

    JeyCi

    Пользователь

    Сообщений: 3357
    Регистрация: 27.11.2013

    #10

    28.08.2014 10:03:54

    Цитата
    zotov пишет: Книжки по программированию каждый день нужно перелистывать тем программистам, которые вынуждают допиливать их «суперпродукты».

    им это уже не нужно — потому что они уже всё пролистали когда-то — и теперь спокойно допиливают под нужды заказчика — если заказчик капризный попадается…

    Цитата
    zotov пишет: Скобки убрал. Но все-таки интересует «первый диапазон». Может быть метод не подходящий?

    не подходящий для чего, для кого, для какой задачи?..

    синтаксис ikki вам поправил на правильный


    нужно вам вникать в ваш код — что не подходит? почему не подходит?… и подсматривать в книжках  ;)   — чем заменить… если не подошло…
    p.s.
    на

    все будущие случаи жизни

    :

    Код
    Sub LastRowInOneColumn()
    'последняя заполненная строка в столбце: столбец А в этом примере
        Dim LastRow As Long
        With ActiveSheet
         LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        End With
        MsgBox LastRow
    End Sub

    или

    Код
    Sub LastColumnInOneRow()
    'последний заполненный столбец в строке: строка 1 в этом примере
        Dim LastCol As Integer
        With ActiveSheet
         LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        End With
        MsgBox LastCol
    End Sub

    и далее упрощённо можно записывать так Range(Cells(1,1),Cells(LastRow,LastCol)) — диапазон от ячейки А1 до последней строки последнего столбца… или модифицировать под свои нужды

    Изменено: JeyCi28.08.2014 18:40:43

    чтобы не гадать на кофейной гуще, кто вам отвечает и после этого не совершать кучу ошибок — обратитесь к собеседнику на ВЫ — ответ на ваш вопрос получите — а остальное вас не касается (п.п.п. на форумах)

     

    zotov

    Пользователь

    Сообщений: 57
    Регистрация: 23.07.2014

    #11

    28.08.2014 18:11:58

    Цитата
    JeyCi пишет: спокойно допиливают под нужды заказчика — если заказчик капризный попадается…

    В случае если программа которая производит сложные вычисления, заявлена как рабочая и не способна на некоторые обязательные, простейшие операции, да к тому-же стоящая как приличный автомобиль… о капризах говорить не совсем правильно.
    Хотя, всегда найдутся разные, однозначные мнения.
    Ну…Вернемся! По теме успехов пока нет…
    Попробую объяснить так

    Прикрепленные файлы

    • Книга1.xlsm (23.35 КБ)
    • База данных.xlsx (10.65 КБ)

    Изменено: zotov28.08.2014 23:51:02

     

    JeyCi

    Пользователь

    Сообщений: 3357
    Регистрация: 27.11.2013

    #12

    28.08.2014 18:32:39

    Цитата
    zotov пишет: В случае если программа которая производит сложные вычисления, заявлена как рабочая и не способна на некоторые обязательные, простейшие операции, да к тому-же стоящая как приличный автомобиль… о капризах говорить не совсем правильно. Хотя, всегда найдутся разные, однозначные мнения. Ну…Вернемся!

    НЕТ… я уже не вернусь… вы или заказывайте в программу все свои поправки разработчику сразу… чтобы он потом не допиливал… или если хотите допиливать сами через безвозмездную помощь на форуме, то — сколько она стоит, и что вам в ней не нравится за ту цену, за которую вы её покупали… о чём говорить правильно, а о чём говорить не правильно, кому какие книжки читать…  —  вы с этими речами и временем на их выслушивание — к разработчику, а не за помощью… если только в 11-м посте вы заявляете вашу реальную проблему… не обессудьте  :(

    Изменено: JeyCi28.08.2014 18:32:54

    чтобы не гадать на кофейной гуще, кто вам отвечает и после этого не совершать кучу ошибок — обратитесь к собеседнику на ВЫ — ответ на ваш вопрос получите — а остальное вас не касается (п.п.п. на форумах)

     

    zotov

    Пользователь

    Сообщений: 57
    Регистрация: 23.07.2014

    JeyCi, Вообще-то вернутся я призывал самого себя… Простите за то что ненароком обидел. В файле у меня не проблема (выход из ситуации простой)
    Для меня эта ситуация является простым неудобством (порядка захотелось), но в других реалиях может кому-то сильно навредить
    Мои текущие проблемы с прогами не для эксель-форумов, максимум для курилки. Но все-равно, спасибо Вам!

     

    ikki

    Пользователь

    Сообщений: 9709
    Регистрация: 22.12.2012

    #14

    28.08.2014 19:11:29

    Цитата
    zotov пишет:
    В случае если программа которая производит сложные вычисления, заявлена как рабочая и не способна на некоторые обязательные, простейшие операции, да к тому-же стоящая как приличный автомобиль…

    если Вы будете эксплуатировать ваш автомобиль, который стоит как автомобиль, неправильно — например, заливать в бензобак керосин, то и результаты будут соответствующие.

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

    фрилансер Excel, VBA — контакты в профиле
    «Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

     

    zotov

    Пользователь

    Сообщений: 57
    Регистрация: 23.07.2014

    ikki, Вы для чего это здесь пишите? Как это здесь влияет на решение задачи? Не в состоянии  помочь? Не хотите помочь? Другие цели?

     

    ikki

    Пользователь

    Сообщений: 9709
    Регистрация: 22.12.2012

    #16

    28.08.2014 19:56:09

    Цитата
    zotov пишет: Не хотите помочь?

    вот! этот вариант подчеркните, пожалуйста.
    с одним дополнением: именно Вам, с Вашим отношением — больше не хочу.
    и прощайте.

    фрилансер Excel, VBA — контакты в профиле
    «Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

     

    zotov

    Пользователь

    Сообщений: 57
    Регистрация: 23.07.2014

    #17

    28.08.2014 20:05:58

    ikki, Вполне разумно. Мое отношение к вам изменилось только-что. Успехов.

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

    Другие методы поиска последней ячейки

    Что ж, это должно охватывать основы поиска последней
    использованной или непустой ячейки на листе. Если ваш лист содержит объекты
    (таблицы, диаграммы, сводные таблицы, слайсеры и т. Д.), Вам может
    потребоваться использовать другие методы для поиска последней ячейки. Я объясню
    эти методы в отдельном посте.

    У меня также есть статья о том, как найти ПЕРВУЮ ячейку в листе.

    Пожалуйста, оставьте комментарий ниже, если у вас есть какие-либо вопросы, или вы все еще не можете найти последнюю ячейку. Я буду рад помочь!

    Finding last used row and column is one of the basic and important task for any automation in excel using VBA. For compiling sheets, workbooks and arranging data automatically, you are required to find the limit of the data on sheets.

    This article will explain every method of finding last row and column in excel in easiest ways.
    1. Find Last Non-Blank Row in a Column using Range.End
    Let’s see the code first. I’ll explain it letter.

    Sub getLastUsedRow()
    
        Dim last_row As Integer
    
        last_row = Cells(Rows.Count, 1).End(xlUp).Row ‘This line gets the last row
    
        Debug.Print last_row 
    
    End Sub

    The the above sub finds the last row in column 1.

    How it works?
    It is just like going to last row in sheet and then pressing CTRL+UP shortcut.
    Cells(Rows.Count, 1): This part selects cell in column A. Rows.Count gives 1048576, which is usually the last row in excel sheet.

    Cells(1048576, 1)

    .End(xlUp): End is an method of range class which is used to navigate in sheets to ends. xlUp is the variable that tells the direction. Together this command selects the last row with data.

    Cells(Rows.Count, 1).End(xlUp)

    .Row : row returns the row number of selected cell. Hence we get the row number of last cell with data in column A. in out example it is 8.

    See how easy it is to find last rows with data. This method will select last row in data irrespective of blank cells before it. You can see that in image that only cell A8 has data. All preceding cells are blank except A4.

    Select the last cell with data in a column
    If you want to select the last cell in A column then just remove “.row” from end and write .select.

    Sub getLastUsedRow()
    
    Cells(Rows.Count, 1).End(xlUp).Select ‘This line selects the last cell in a column
    
    End Sub

    The “.Select” command selects the active cell.
    Get last cell’s address column
    If you want to get last cell’s address in A column then just remove “.row” from end and write .address.

    Sub getLastUsedRow()
    
    add=Cells(Rows.Count, 1).End(xlUp).address ‘This line selects the last cell in a column
    Debug.print add
    End Sub

    The Range.Address function returns the activecell’s address.
    Find Last Non-Blank Column in a Row
    It is almost same as finding last non blank cell in a column. Here we are getting column number of last cell with data in row 4.

    Sub getLastUsedCol()
    
        Dim last_col As Integer
    
        last_col = Cells(4,Columns.Count).End(xlToLeft).Column ‘This line gets the last column
    
        Debug.Print last_col
    
    End Sub


    You can see in image that it is returning last non blank cell’s column number in row 4. Which is 4.
    How it works?

    Well, the mechanics is same as finding last cell with data in a column. We just have used keywords related to columns.
    Select Data Set in Excel Using VBA
    Now we know, how to get last row and last column of excel using VBA. Using that we can select a table or dataset easily. After selecting data set or table, we can do several operations on them, like copy-paste, formating, deleting etc.
    Here we have data set. This data can expand downwards. Only the starting cell is fixed, which is B4. The last row and column is not fixed. We need to select the whole table dynamically using vba.

    VBA code to select table with blank cells

    Sub select_table()
    Dim last_row, last_col As Long
    
    'Get last row
    last_row = Cells(Rows.Count, 2).End(xlUp).Row
    
    'Get last column
    last_col = Cells(4, Columns.Count).End(xlToLeft).Column
    
    'Select entire table
    Range(Cells(4, 2), Cells(last_row, last_col)).Select
    
    End Sub

    When you run this, entire table will be selected in fraction of a second. You can add new rows and columns. It will always select the entire data.

    Benefits of this method:

    1. It’s easy. We literally wrote only one line to get last row with data. This makes it easy.
    2. Fast. Less line of code, less time taken.
    3. Easy to understand.
    4. Works perfectly if you have clumsy data table with fixed starting point. 

    Cons of Range.End method:

    1. The starting point must be know.
    2. You can only get last non-blank cell in a known row or column. When your starting point is not fixed, it will be useless. Which is very less likely to happen.

    2. Find Last Row Using Find() Function
    Let’s see the code first.

    Sub last_row()
    
       lastRow = ActiveSheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
     
       Debug.Print lastRow
    
    End Sub
    


    As you can see that in image, that this code returns the last row accurately.
    How it works?
    Here we use find function to find any cell that contains any thing using wild card operator «*». Asterisk is used to find anything, text or number.

    We set search order by rows (searchorder:=xlByRows). We also tell excel vba the direction of search as xlPrevious (searchdirection:=xlPrevious). It makes find function to search from end of the sheet, row wise.
    
    Once it find a cell that contains anything, it stops. We use the Range.Row method to fetch last row from active cell.

    Benefits of Find function for getting last cell with data:

    1. You don’t need to know the starting point. It just gets you last row. 
    2. It can be generic and can be used to find last cell with data in any sheet without any changes.
    3. Can be used to find any last instance of specific text or number on sheet.

    Cons of Find() function:

    1. It is ugly. Too many arguments.
    2. It is slow.
    3. Can’t use to get last non blank column. Technically, you can. But it gets too slow.

    3. Using SpecialCells Function To Get Last Row
    The SpecialCells function with xlCellTypeLastCell argument returns the last used cell. Lets see the code first

    Sub spl_last_row_()
    lastRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
    Debug.Print lastRow
    End Sub


    If you run the above code, you will get row number of last used cell.

    How it Works?

    This is the vba equivalent of shortcut CTRL+End in excel. It selects the last used cell. If record the macro while pressing CTRL+End, you will get this code.

    Sub Macro1()
    '
    ' Macro1 Macro
    '
    
    '
        ActiveCell.SpecialCells(xlLastCell).Select
    End Sub
    

    We just used it to get last used cell’s row number.

    Note: As I said above, this method will return the last used cell not last cell with data. If you delete the data in last cell, above vba code will still return the same cells reference, since it was the “last used cell”. You need to save the document first to get last cell with data using this method.

    Related Articles:

    Delete sheets without confirmation prompts using VBA in Microsoft Excel

    Add And Save New Workbook Using VBA In Microsoft Excel 2016

    Display A Message On The Excel VBA Status Bar

    Turn Off Warning Messages Using VBA In Microsoft Excel 2016

    Popular Articles:

    The VLOOKUP Function in Excel

    COUNTIF in Excel 2016

    How to Use SUMIF Function in Excel

    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

    In VBA, when we have to find the last row, there are many different methods. The most commonly used method is the End(XLDown) method. Other methods include finding the last value using the find function in VBA, End(XLDown). The row is the easiest way to get to the last row.

    Excel VBA Last Row

    If writing the code is your first progress in VBA, then making the code dynamic is your next step. Excel is full of cell referencesCell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1.read more. The moment we refer to the cell, it becomes fixed. If our data increases, we need to go back to the cell reference and change the references to make the result up to date.

    For an example, look at the below code.

    Code:

    Sub Last_Row_Example1()
    
       Range("D2").Value = WorksheetFunction.Sum(Range("B2:B7"))
    
    End Sub

    VBA Last Row Sum 1

    The above code says in D2 cell value should be the summation of Range (“B2:B7”).

    VBA Last Row Sum 1-1

    Now, we will add more values to the list.

    VBA Last Row Sum 1-2

    Now, if we run the code, it will not give us the updated result. Rather, it still sticks to the old range, i.e., Range (“B2: B7”).

    That is where dynamic code is very important.

    Finding the last used row in the column is crucial in making the code dynamic. This article will discuss finding the last row in Excel VBA.

    Table of contents

    • Excel VBA Last Row
      • How to Find Last Used Row in the Column?
        • Method #1
        • Method #2
        • Method #3
      • Recommended Articles

    How to Find the Last Used Row in the Column?

    Below are the examples to find the last used row in Excel VBA.

    You can download this VBA Last Row Template here – VBA Last Row Template

    Method #1

    Before we explain the code, we want you to remember how you go to the last row in the normal worksheet.

    We will use the shortcut key Ctrl + down arrow.

    It will take us to the last used row before any empty cell. We will also use the same VBA method to find the last row.

    Step 1: Define the variable as LONG.

    Code:

    Sub Last_Row_Example2()
        
       Dim LR As Long
       'For understanding LR = Last Row
    End Sub

    VBA Last Row Method 1

    Step 2: We will assign this variable’s last used row number.

    Code:

    Sub Last_Row_Example2()
    
       Dim LR As Long
       'For understanding LR = Last Row
    
       LR =
    
    End Sub

    Step 3: Write the code as CELLS (Rows.Count,

    Code:

    Sub Last_Row_Example2()
    
       Dim LR As Long
       'For understanding LR = Last Row
    
       LR = Cells(Rows.Count,
    
    End Sub

    VBA Last Row Method 1-2

    Step 4: Now, mention the column number as 1.

    Code:

    Sub Last_Row_Example2()
    
       Dim LR As Long
       'For understanding LR = Last Row
       LR = Cells(Rows.Count, 1)
    
    End Sub

    VBA Last Row Method 1-3

    CELLS(Rows.Count, 1) means counting how many rows are in the first column.

    So, the above VBA code will take us to the last row of the Excel sheet.

    Step 5: If we are in the last cell of the sheet to go to the last used row, we will press the Ctrl + Up Arrow keys.

    In VBA, we need to use the end key and up, i.e., End VBA xlUpVBA XLUP is a range and property method for locating the last row of a data set in an excel table. This snippet works similarly to the ctrl + down arrow shortcut commonly used in Excel worksheets.read more

    Code:

    Sub Last_Row_Example2()
    
       Dim LR As Long
       'For understanding LR = Last Row
    
       LR = Cells(Rows.Count, 1).End(xlUp)
    
    End Sub

    VBA Last Row Method 1-4

    Step 6: It will take us to the last used row from the bottom. Now, we need the row number of this. So, use the property ROW to get the row number.

    Code:

    Sub Last_Row_Example2()
    
      Dim LR As Long
      'For understanding LR = Last Row
    
      LR = Cells(Rows.Count, 1).End(xlUp).Row
    
    End Sub

    VBA Last Row Method 1-5

    Step 7: Now, the variable holds the last used row number. Show the value of this variable in the message box in the VBA codeVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

    Code:

    Sub Last_Row_Example2()
    
      Dim LR As Long
      'For understanding LR = Last Row
    
      LR = Cells(Rows.Count, 1).End(xlUp).Row
    
      MsgBox LR
    
    End Sub

    VBA Last Row Method 1-6

    Run this code using the F5 key or manually. It will display the last used row.

    VBA Last Row Method 1-7

    Output:

    VBA Last Row Method 1-8

    The last used row in this worksheet is 13.

    Now, we will delete one more line, run the code, and see the dynamism of the code.

    VBA Last Row Method 1-9

    Now, the result automatically takes the last row.

    That is what the dynamic VBA last row code is.

    As we showed in the earlier example, change the row number from a numeric value to LR.

    Code:

    Sub Last_Row_Example2()
    
       Dim LR As Long
       'For understanding LR = Last Row
    
        LR = Cells(Rows.Count, 1).End(xlUp).Row
    
        Range("D2").Value = WorksheetFunction.Sum(Range("B2:B" & LR))
    
    End Sub

    VBA Last Row Method 1-10

    We have removed B13 and added the variable name LR.

    Now, it does not matter how many rows you add. It will automatically take the updated reference.

    Method #2

    We can also find the last row in VBA using the Range objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more and special VBA cells propertyCells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells.read more.

    Code:

    Sub Last_Row_Example3()
    
       Dim LR As Long
    
       LR = Range("A:A").SpecialCells(xlCellTypeLastCell).Row
    
       MsgBox LR
    End Sub

    Method 2

    The code also gives you the last used row. For example, look at the below worksheet image.

    Method 2-1

    If we run the code manually or use the F5 key result will be 12 because 12 is the last used row.

    VBA Last Row Method 2-3

    Output:

    Method 2-2

    Now, we will delete the 12th row and see the result.

    Method 2-4

    Even though we have deleted one row, it still shows the result as 12.

    To make this code work, we must hit the “Save” button after every action. Then this code will return accurate results.

    We have saved the workbook and now see the result.

    Method 2-5

    Method #3

    We can find the VBA last row in the used range. For example, the below code also returns the last used row.

    Code:

    Sub Last_Row_Example4()
    
       Dim LR As Long
    
       LR = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row
    
       MsgBox LR
    End Sub

    Method 3

    It will also return the last used row.

    VBA Last Row Method 3-1

    Output:

    Method 3-2

    Recommended Articles

    This article has been a guide to VBA Last Row. Here, we learn the top 3 methods to find the last used row in a given column, along with examples and downloadable templates. Below are some useful articles related to VBA: –

    • How to Record Macros in VBA Excel?
    • Create VBA Loops
    • ListObjects in VBA

    VBA Last Row or Column with Data


    It is important to know how to generate a code that identifies the address of the last row or column with data from a spreadsheet. It is useful as a final counter in Loops and as a reference for intervals.

    VBA Count

    The .Count property, when used for a Range object, returns the number of cells in a given range. (whether they are filled or not).

        MsgBox Range("A1:B7").Count 'Returns 14
    

    If you want to know the number of columns or of rows of a given range, you can use the Columns or the Rows properties in conjunction with the Count property.

        MsgBox Range("A1:B7").Rows.Count    'Returns 7
        MsgBox Range("A1:B7").Columns.Count 'Returns 2
    

    The .Count property returns the number of objects of a given collection.

    If you want to know the number of rows or columns in the worksheet, you can use Rows or Columns without specifying the cells with the Range:

        MsgBox "The number of rows in the worksheet is: " & Rows.Count
    

    Rows Total

        MsgBox "The number of columns in the worksheet is: " & Columns.Count
    

    Columns Total


    VBA End

    Although the Count property is very useful, it returns only the available amount of elements, even if they are without values.

    The End property, used in conjunction with the Range object, will return the last cell with content in a given direction. It is equivalent to pressing
    Ctrl +
    (Seta para esquerda or
    Seta para cima or
    Seta para baixo or
    Seta para direita).

        Range("A1").End(xlDown).Select
        'Range("A1").End([direction]).Select
    

    End Select

    When using End it is necessary to define its argument, the direction: xlUp, xlToRight, xlDown, xlToLeft.

    You can also use the end of the worksheet as reference, making it easy to use the xlUp argument:

    End Example

        MsgBox "The last row with data is number: " & Cells(Rows.Count, 1).End(xlUp).Row
    

    MsgBox End(xlUp)


    VBA Last Cell Filled

    Note that there are some ways to determine the last row or column with data from a spreadsheet:

        Range("A1").End(xlDown).Row
        'Determines the last row with data from the first column
    
        Cells(Rows.Count, 1).End(xlUp).Row
        'Determines the last row with data from the first column
    
        Range("A1").End(xlToRight).Column
        'Determines the last column with data from the first row
    
        Cells(1,Columns.Count).End(xlToLeft).Column
        'Determines the last column with data from the first row
    

    Show Advanced Topics



    Consolidating Your Learning

    Suggested Exercises



    SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

    Excel ® is a registered trademark of the Microsoft Corporation.

    © 2023 SuperExcelVBA | ABOUT

    Protected by Copyscape

    Понравилась статья? Поделить с друзьями:
  • Vba excel cells find what
  • Vba excel cell диапазон
  • Vba excel cell column
  • Vba excel can t find project or library
  • Vba excel can t enter break mode at this time