Excel vba определение количества строк

Home / VBA / Count Rows using VBA in Excel

To count rows using VBA, you need to define the range from which you want to count the rows and then use the count and rows property to get the count of the row from that range. You can also use a loop to count rows where you have data only.

Use VBA to Count Rows

  1. First, you need to define the range for which you want to count the rows.
  2. After that, use a dot (.) to open the list of properties and methods.
  3. Next, type or select the “Rows” property.
  4. In the end, use the “Count” property.
vba-to-count-rows

Now when you run this code, it will return the count of the rows, and to get the count you can use a message box or directly enter that value into a cell as well.

Sub vba_count_rows()
Range("A1:A10").Rows.Count
End Sub

Count Rows for the Used Range

Sub vba_count_rows2()
   MsgBox Worksheets("Sheet1").UsedRange.Rows.Count
End Sub

Count Rows with Data using VBA

You can also count rows where you have data by ignoring the blank rows.

count-rows-with-data-using-vba

The following code will take the used range as the range to loop up at and loop through each row one by one and check if there’s a non-empty cell there, and if it is there it will consider it as a row with data, and in the end, show a message box with the total count of rows.

Sub vba_count_rows_with_data()

Dim counter As Long
Dim iRange As Range

With ActiveSheet.UsedRange

    'loop through each row from the used range
    For Each iRange In .Rows

        'check if the row contains a cell with a value
        If Application.CountA(iRange) > 0 Then

            'counts the number of rows non-empty Cells
            counter = counter + 1

        End If

    Next

End With

MsgBox "Number of used rows is " & counter
End Sub

More Tutorials

    • 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
    • Find Last Row, Column, and 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

    Excel VBA Row Count

    In VBA programming, referring to rows is most important as well, and counting them is one thing you must be aware of when it comes to VBA coding. We can get a lot of value if we understand the importance of counting rows with data in the worksheet. This article will show you how to count rows using VBA coding.

    VBA Row Count

    Table of contents
    • Excel VBA Row Count
      • How to Count Rows in VBA?
        • Example #1
        • Example #2
        • Example #3 – Find Last Used Row
      • Things to Remember
      • Recommended Articles

    How to Count Rows in VBA?

    You can download this VBA Row Count Excel Template here – VBA Row Count Excel Template

    Example #1

    To count rowsThere are numerous ways to count rows in Excel using the appropriate formula, whether they are data rows, empty rows, or rows containing numerical/text values. Depending on the circumstance, you can use the COUNTA, COUNT, COUNTBLANK, or COUNTIF functions.read more, we need to use the RANGE object. In this object, we need to use the ROWS object. In this, we need to use the COUNT property.

    Look at the below data in Excel.

    VBA Row Count Example 1

    From the above data, we need to identify how many rows are there from the range A1 to A8. So first, define the variable as an Integer to store the number of rows.

    Code:

    Sub Count_Rows_Example1()
    
    Dim No_Of_Rows As Integer
    
    End Sub

    VBA Row Count Example 1-1

    We will assign row numbers for this variable, so enter the variable name and the equal sign.

    Code:

    Sub Count_Rows_Example1()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows =
    
    End Sub

    VBA Row Count Example 1-2

    We need to provide a range of cells, so open 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 supply the range as “A1:A8”. 

    Code:

    Sub Count_Rows_Example1()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows = Range("A1:A8")
    
    End Sub

    VBA Row Count Example 1-3

    Once we supply the range, we need to count the number of rows, so choose the ROWS property of the RANGE object.

    VBA Row Count Example 1-4

    We are counting several rows in the RANGE object’s ROWS property, so choose the “COUNT” property now.

    VBA Row Count Example 1-7

    Now in the message box, show the value of the variable.

    Code:

    Sub Count_Rows_Example1()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows = Range("A1:A8").Rows.Count
    
    MsgBox No_Of_Rows
    
    End Sub

    VBA Row Count Example 1-5

    Now, run the code and see the count of rows of the supplied range of cells.

    VBA Row Count Example 1-6

    There are 8 rows supplied for the range, so the row count is 8 in the message box.

    Example #2

    We have other ways of counting rows as well. For the above method, we need to supply a range of cells, showing the number of rows selected.

    But imagine the scenario where we need to find the last use of any column. For example, take the same data as seen above.

    VBA Row Count Example 1

    To move to the last used cell from cell A1, we press the shortcut excel keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more “Ctrl + Down Arrow,” so it will take you to the last cell before the empty cell.

    First, supply the cell as A1 using the RANGE object.

    Code:

    Sub Count_Rows_Example2()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows = Range("A1")
    
    MsgBox No_Of_Rows
    
    End Sub

    VBA Row Count Example 2

    From this cell, we need to move down. We use Ctrl + Down Arrow in the worksheet, but in VBA, we use the END propertyEnd is a VBA statement that can be used in a variety of ways in VBA applications. Anywhere in the code, a simple End statement can be used to instantly end the execution of the code. In procedures, the end statement is used to end a subprocedure or any loop function, such as ‘End if’.read more. Choose this property and open the bracket to see options.

    Example 2-1

    Look there with the END key. We can see all the arrow keys like “xlDown, xlToLeft, xlToRight, and xlUp” since we need to move down and use the “xlDown” option.

    Code:

    Sub Count_Rows_Example2()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows = Range("A1").End(xlDown)
    
    MsgBox No_Of_Rows
    
    End Sub

    Example 2-2

    It will take you to the last cell before any break. We need the row number in the active cellThe active cell is the currently selected cell in a worksheet. Active cell in VBA can be used as a reference to move to another cell or change the properties of the same active cell or the cell’s reference provided from the active cell.read more so use the ROW property.

    Code:

    Sub Count_Rows_Example2()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows = Range("A1").End(xlDown).Row
    
    MsgBox No_Of_Rows
    
    End Sub

    Example 2-3

    Now, this will show the last row numberThe End(XLDown) method is the most commonly used method in VBA to find the last row, but there are other methods, such as finding the last value in VBA using the find function (XLDown).read more, which will be the count of the number of rows.

    VBA Row Count Example 2-4

    So in rows, we have data.

    Example #3 – Find Last Used Row

    Finding the last used row is important to decide how many times the loop has to run. Also, in the above method, the last row stops to select if there is any breakpoint cell. So in this method, we can find the last used row without any problems.

    Open CELL 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 Count_Rows_Example3()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows = Cells(
    
    MsgBox No_Of_Rows
    
    End Sub

    VBA Row Count Example 3

    Now, we need to mention the row number to start with. The problem here is we are not sure how many rows of data we have so that we can go straight to the last row of the worksheet, for this mention, ROWS.COUNT property.

    Code:

    Sub Count_Rows_Example3()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows = Cells(Rows.Count,
    
    MsgBox No_Of_Rows
    
    End Sub

    Example 3-1

    Next, we need to mention in which column we are finding the last used row, so in this case, we are finding it in the first column, so mention 1.

    Code:

    Sub Count_Rows_Example3()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows = Cells(Rows.Count, 1)
    
    MsgBox No_Of_Rows
    
    End Sub

    Example 3-2

    At this moment, it will take you to the last cell of the first column. We need to move upwards to the last used cell from there onwards, so use the End(xlUp) property.

    Code:

    Sub Count_Rows_Example3()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows = Cells(Rows.Count, 1).End(xlUp)
    
    MsgBox No_Of_Rows
    
    End Sub

    Example 3-3

    So, this will take you to the last used cell of column 1, and in this cell, we need the row number, so use the ROW property to get the row number.

    Code:

    Sub Count_Rows_Example3()
    
    Dim No_Of_Rows As Integer
    
    No_Of_Rows = Cells(Rows.Count, 1).End(xlUp).Row
    
    MsgBox No_Of_Rows
    
    End Sub

    VBA Row Count Example 3-4

    Things to Remember

    • The COUNT will give several rows in the worksheet.
    • If you have a range, then it will give several rows selected in the range.
    • The ROW property will return the active cell row number.

    Recommended Articles

    This article has been a guide to VBA Row Count. Here, we discuss how to count used rows in Excel using VBA coding, practical examples, and a downloadable Excel template. You may learn more about Excel from the following articles: –

    • VBA Insert Row
    • VBA Delete Row
    • VBA StatusBar
    • VBA Variable Range

    This tutorial shows how to count the total number of rows from a selected range through the use of an Excel formula or VBA

    Example: Count number of rows in a range

    Count number of rows in a range

    METHOD 1. Count number of rows in a range

    EXCEL

    This formula uses the Excel ROWS function to return the number of rows in the selected range. In this example we have selected range (E5:E15) inside the ROWS function, which returns a total of 11 rows.

    METHOD 1. Count number of rows in a range using VBA

    VBA

    Sub Count_number_of_rows_in_range()

    ‘declare a variable
    Dim ws As Worksheet

    Set ws = Worksheets(«Analysis»)

    ‘count the total number of rows in a specific range
    ws.Range(«B5») = ws.Range(«E5:E15»).Rows.Count

    End Sub

    ADJUSTABLE PARAMETERS
    Output Range: Select the output range by changing the cell reference («B5») in the VBA code.
    Range: Select the range from which you want to count the number of rows by changing the range reference («E5:E15») in the VBA code.
    Worksheet Selection: Select the worksheet in which you want to count the number of rows from a selected range by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.

    Explanation about the formula used to count number of rows in a range

    EXPLANATION

    EXPLANATION

    This tutorial shows how to count the total number of rows from a selected range through the use of an Excel formula or VBA.

    Both the Excel formula and VBA approach make use of the ROWS function to count the number of rows in a selected range.

    Using the VBA method you will also need to combine the Rows function with the Count function to return the total number of rows in a selected range.

    FORMULA
    =ROWS(array)

    ARGUMENTS
    array: An array or reference to a range of cells.

    Related Topic Description Related Topic and Description
    Count number of columns in a range How to count the total number of columns in a range using Excel and VBA methods
    Count number of cells in a range How to count the total number of cells in a range using Excel and VBA methods
    Count number of characters in a cell How to count the total number of characters, including spaces, in a cell using Excel and VBA methods
    Count number of characters in a cell excluding spaces How to count the total number of characters in a cell, excluding spaces, using Excel and VBA methods
    Count number of characters in a range How to ccount the total number of characters in a range, including spaces, using Excel and VBA methods
    Related Functions Description Related Functions and Description
    ROWS Function The Excel ROWS function returns the number of rows in a specified array

    Содержание

    1. Свойство Application.Rows (Excel)
    2. Синтаксис
    3. Примечания
    4. Пример
    5. Поддержка и обратная связь
    6. Свойство Range.Rows (Excel)
    7. Синтаксис
    8. Замечания
    9. Пример
    10. Поддержка и обратная связь
    11. Count Rows using VBA in Excel
    12. Use VBA to Count Rows
    13. Count Rows for the Used Range
    14. Count Rows with Data using VBA
    15. Как узнать количество строк в excel vba
    16. Как посчитать количество строк в Excel
    17. Описание функции
    18. Пример
    19. Код на VBA
    20. Как получить количество строк в EXCEL VBA
    21. Vba excel как определить количество строк
    22. Как подсчитать общее количество строк в таблице в Excel?

    Свойство Application.Rows (Excel)

    Возвращает объект Range , представляющий все строки на активном листе. Если активный документ не является листом, свойство Rows завершается ошибкой . Объект Range предназначен только для чтения.

    Синтаксис

    expression. Строк

    выражение: переменная, представляющая объект Application.

    Примечания

    Использование этого свойства без квалификатора объекта эквивалентно использованию ActiveSheet.Rows.

    При применении к объекту Range , который является множественным выделением, это свойство возвращает строки только из первой области диапазона. Например, если объект Range имеет две области — A1:B2 и C3:D4, selection.Rows.Count возвращает 2, а не 4.

    Чтобы использовать это свойство в диапазоне, который может содержать несколько выделенных элементов, проверьте Areas.Count, чтобы определить, является ли диапазон множественным выбором. Если это так, выполните цикл по каждой области диапазона, как показано в третьем примере.

    Пример

    В этом примере удаляется третья строка на листе Sheet1.

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

    В этом примере отображается количество строк в выделенном фрагменте на листе Sheet1. Если выбрано несколько областей, в примере выполняется цикл по каждой области.

    Поддержка и обратная связь

    Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

    Источник

    Свойство Range.Rows (Excel)

    Возвращает объект Range , представляющий строки в указанном диапазоне.

    Синтаксис

    expression. Строк

    выражение: переменная, представляющая объект Range.

    Замечания

    Чтобы вернуть одну строку, используйте свойство Item или аналогично включите индекс в круглые скобки. Например, и Selection.Rows(1) Selection.Rows.Item(1) возвращают первую строку выделенного фрагмента.

    При применении к объекту Range , который является множественным выделением, это свойство возвращает строки только из первой области диапазона. Например, если объект someRange Range имеет две области — A1:B2 и C3:D4, someRange.Rows.Count возвращает значение 2, а не 4. Чтобы использовать это свойство в диапазоне, который может содержать несколько выделенных элементов, проверьте Areas.Count , чтобы определить, является ли диапазон множественным выбором. Если это так, выполните цикл по каждой области диапазона, как показано в третьем примере.

    Возвращаемый диапазон может находиться за пределами указанного диапазона. Например, Range(«A1:B2»).Rows(5) возвращает ячейки A5:B5. Дополнительные сведения см. в разделе Свойство Item .

    Использование свойства Rows без квалификатора объекта эквивалентно использованию ActiveSheet.Rows. Дополнительные сведения см. в свойстве Worksheet.Rows .

    Пример

    В этом примере удаляется диапазон B5:Z5 на листе 1 активной книги.

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

    В этом примере отображается количество строк в выделенном фрагменте на листе Sheet1. Если выбрано несколько областей, в примере выполняется цикл по каждой области.

    Поддержка и обратная связь

    Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

    Источник

    Count Rows using VBA in Excel

    To count rows using VBA, you need to define the range from which you want to count the rows and then use the count and rows property to get the count of the row from that range. You can also use a loop to count rows where you have data only.

    Use VBA to Count Rows

    1. First, you need to define the range for which you want to count the rows.
    2. After that, use a dot (.) to open the list of properties and methods.
    3. Next, type or select the “Rows” property.
    4. In the end, use the “Count” property.

    Now when you run this code, it will return the count of the rows, and to get the count you can use a message box or directly enter that value into a cell as well.

    Count Rows for the Used Range

    Count Rows with Data using VBA

    You can also count rows where you have data by ignoring the blank rows.

    The following code will take the used range as the range to loop up at and loop through each row one by one and check if there’s a non-empty cell there, and if it is there it will consider it as a row with data, and in the end, show a message box with the total count of rows.

    Источник

    Как узнать количество строк в excel vba

    Как посчитать количество строк в Excel

    Описание функции

    Функция =КОЛИЧЕСТВОСТРОК( [ССЫЛКА] ) имеет один необязательный аргумент.

    • [ССЫЛКА] — Ссылка на любую ячейку листа, в котором необходимо посчитать количество строк. По умолчанию (если аргумент не указан) функция применяется к активному листу.

    Ниже приведен пример работы данной формулы.

    Пример

    Определение количества строк на текущем листе.

    Код на VBA

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

    Как получить количество строк в EXCEL VBA

    Я разрабатываю приборную панель в excel. И я ищу вычисление количества строк. (Сколько записей присутствует)..

    Поскольку есть несколько пустых ячеек, я думал, что они идут снизу вверх. Я использую следующие

    После этого выполнения активная ячейка находится на A113, что означает, что количество строк равно 113.

    Мой вопрос: как получить этот номер 113 из активной ячейки?

    Вы можете использовать это:

    lastrow будет содержать номер последней пустой строки в столбце A , в вашем случае 113

    Вот что я обычно использую для этого:

    Это вернет число непустых ячеек в столбце “А”, что, как я думаю, вам нужно. Надеюсь это поможет.

    Если есть небольшая вероятность того, что последняя строка рабочего листа не пуста, вы должны добавить проверку IsEmpty() в решение @simoco. Следовательно; следующая – это функция, которая возвращает последнюю использованную строку и проверяет, является ли последняя строка листа пустой:

    Источник

    Vba excel как определить количество строк

    Как подсчитать общее количество строк в таблице в Excel?

    В этой статье говорится о подсчете общего количества строк в указанной таблице в Excel. Пожалуйста, сделайте следующее.

    Удивительный! Использование эффективных вкладок в Excel, таких как Chrome, Firefox и Safari!
    Экономьте 50% своего времени и сокращайте тысячи щелчков мышью каждый день!

    Приведенный ниже код VBA может помочь вам подсчитать количество строк в указанной таблице в Excel.

    1. нажмите другой + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

    2. в Microsoft Visual Basic для приложений окно, пожалуйста, нажмите Вставить > Модули. Затем скопируйте и вставьте приведенный ниже код VBA в окно модуля.

    Код VBA: подсчитать общее количество строк в таблице в Excel

    3. нажмите F5 ключ для запуска кода.

    4. В дебюте Kutools for Excel в диалоговом окне введите имя таблицы, в которой необходимо подсчитать общее количество строк, а затем нажмите кнопку OK кнопка. Смотрите скриншот:

    5. Теперь еще один Kutools for Excel появится диалоговое окно, в котором показано, сколько строк существует в этой указанной таблице, щелкните значок OK для завершения.

    Источник

     

    Елена Дроздова

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

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

    #1

    15.06.2022 11:07:12

    Добрый день!
    Пытаюсь посчитать количество строк в умной таблице. Подскажите, пожалуйста, почему строка выдает ошибку 438?

    Код
    LastRow = Workbooks("Книга1.xlsm").Worksheets("Лист1").ListObject("Таблица1").ListRows.Count
    

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

    • Книга1.xlsm (15.3 КБ)

    Изменено: Елена Дроздова15.06.2022 11:13:39

     

    Jack Famous

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

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

    OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

    #2

    15.06.2022 11:13:29

    Елена Дроздова, здравствуйте

    Цитата
    Елена Дроздова: количество строк в умной таблице

    без шапки и итогов:
    Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).ListObjects(«Таблица1»).ListRows.Count или
    Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).ListObjects(«Таблица1»).DataBodyRange.Rows.Count

    Справка

    Изменено: Jack Famous15.06.2022 13:29:24

    Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

     

    Jack Famous, попробовала — та же ошибка

     

    Jack Famous

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

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

    OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

    Елена Дроздова, значит проблема в имени книги/листа/таблицы
    Для таблицы на активном листе: ActiveSheet.ListObjects(1).DataBodyRange.Rows.Count

    Изменено: Jack Famous15.06.2022 12:24:30

    Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

     

    Jack Famous, не работает. А если мне макросом понадобится открыть другую таблицу и посчитать строки там, то как ссылаться? Все время активировать нужный лист?

     

    RAN

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

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

    #6

    15.06.2022 11:49:28

    Код
    Workbooks("Книга1.xlsm").Worksheets("Лист1").ListObjects("Таблица1").ListRows.Count

    Изменено: RAN15.06.2022 11:50:12

     

    artemkau88

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

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

    #7

    15.06.2022 11:54:40

    Елена Дроздова

    , можно еще использовать SQL запрос (добавил в ознакомительных целях)
    код:

    Код
    Sub Macro()
    Dim myConnect As String, mySQL As String, myRecord As Object
    
        DataRange = "[" & ActiveWorkbook.Sheets(1).Name & "$" & strAddress & "]"
            myConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=" & ActiveWorkbook.FullName & ";" & _
               "Extended Properties=""Excel 12.0;HDR=YES"""
        
        Set myRecord = CreateObject("ADODB.Recordset")
        mySQL = "SELECT COUNT(*) FROM [Лист1$]"
        myRecord.Open mySQL, myConnect
        
    [E1].CopyFromRecordset myRecord
    End Sub
    

    в ячейку E1 выводит количество строк.
    или использовать Ваш макрос:

    Код
    Sub Макрос1()
    Dim myTable As ListObject
    Set myTable = Worksheets(1).ListObjects("Таблица1")
    MsgBox myTable.DataBodyRange.Rows.Count
    ' или: (можете раскомментировать)
    '    LastRow = Range("Таблица1").Rows.Count
    '    MsgBox (LastRow)
    End Sub
    

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

    • Книга1(1).xlsm (17.21 КБ)

     

    Jack Famous

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

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

    OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

    RAN, значит точно не в методах дело, раз ListRows.Count у вас работает — в 1ом сообщении тоже самое

    UPD: ListObjects — у меня на базе ТСа та же ошибка была — поправил везде  :)

    Изменено: Jack Famous15.06.2022 12:26:27

    Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

     

    Елена Дроздова

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

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

    #9

    15.06.2022 13:09:05

    Сработало вот так:

    Код
    Set myobj = Workbooks("Книга1.xlsm").Worksheets("Лист1").ListObjects("Таблица1")
        LastRow = myobj.ListColumns(1).DataBodyRange.Count
        MsgBox (LastRow)
    

    По-другому никак не работает.

     

    Ігор Гончаренко

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

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

    #10

    15.06.2022 13:21:46

    прямо уж никак))

    Код
      Debug.Print myobj.ListRows.Count
      Debug.Print myobj.DataBodyRange.Rows.Count
      Debug.Print myobj.Range.Rows.Count - 1

    Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

     

    Jack Famous

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

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

    OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

    #11

    15.06.2022 13:28:28

    Цитата
    Ігор Гончаренко: прямо уж никак

    да она явно что-то не то пробовала  :D

    Цитата
    Ігор Гончаренко: myobj.Range.Rows.Count — 1

    если есть итоги, то -2  :)

    Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

     

    Елена Дроздова

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

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

    #12

    15.06.2022 14:07:43

    Вы, скорее всего, правы, но у меня не получалось  :)  

    Понравилась статья? Поделить с друзьями:
  • Excel vba описание переменных
  • Excel vba невозможно убрать перенос строк
  • Excel vba описание массива
  • Excel vba не работает функция
  • Excel vba операции со строками