I am developing a dashboard in excel. And I am looking for calculating row count. (How many records are present) ..
Since there are some blank cells I thought to go from bottom to up. I use the following
Range("A1048576").Select
Selection.End(xlUp).Select
After this execution the active cell is at A113 which means the row count is 113.
My question is how to get this number 113 from the active cell?
asked Feb 4, 2014 at 13:37
You can use this:
Dim lastrow as Long
lastrow = Cells(Rows.Count,"A").End(xlUp).Row
lastrow
will contain number of last empty row in column A
, in your case 113
answered Feb 4, 2014 at 13:38
Dmitry PavlivDmitry Pavliv
35.2k13 gold badges79 silver badges80 bronze badges
1
Here is what I usually use for that:
lastrow = WorksheetFunction.CountA(Columns("A:A"))
This will return the number of non-empty cells in Column «A» which is what I think you’re after. Hope this helps.
answered Feb 4, 2014 at 13:49
Jim SimsonJim Simson
2,7663 gold badges21 silver badges30 bronze badges
2
The best way to get the count of rows/records (in most cases) is to use .UsedRange.Rows.Count
. You can assign the return value to a variable like this:
lastRow = Sheets(1).UsedRange.Rows.Count
If you use a function that includes a column (such as column A) as shown in other examples, that will only get you the count of rows in that column, which may or may not be what you’re going for. One caveat: if you have formatted rows below your last row with a value then it will return that row number.
answered Mar 3, 2021 at 0:28
If there is a slight chance that the last row of the worksheet is not empty, you should add an IsEmpty()
check to @simoco ‘s solution. Therefore; following is a function that returns the last used row and check if the last row of the worksheet is empty:
Function lastRow(WS As Worksheet, iColumn As String) As Long
If Not IsEmpty(WS.Range(iColumn & WS.Rows.Count)) Then
lastRow = WS.Rows.Count
Else
lastRow = WS.Range(iColumn & WS.Rows.Count).End(xlUp).Row
End If
End Function
answered Feb 4, 2014 at 14:22
simpLE MAnsimpLE MAn
1,56213 silver badges22 bronze badges
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
- First, you need to define the range for which you want to count the rows.
- After that, use a dot (.) to open the list of properties and methods.
- Next, type or select the “Rows” property.
- 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.
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.
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
Елена Дроздова Пользователь Сообщений: 106 |
#1 15.06.2022 11:07:12 Добрый день!
Прикрепленные файлы
Изменено: Елена Дроздова — 15.06.2022 11:13:39 |
||
Jack Famous Пользователь Сообщений: 10852 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
#2 15.06.2022 11:13:29 Елена Дроздова, здравствуйте
без шапки и итогов: Справка Изменено: Jack Famous — 15.06.2022 13:29:24 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
||
Jack Famous, попробовала — та же ошибка |
|
Jack Famous Пользователь Сообщений: 10852 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
Елена Дроздова, значит проблема в имени книги/листа/таблицы Изменено: Jack Famous — 15.06.2022 12:24:30 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
Jack Famous, не работает. А если мне макросом понадобится открыть другую таблицу и посчитать строки там, то как ссылаться? Все время активировать нужный лист? |
|
RAN Пользователь Сообщений: 7091 |
#6 15.06.2022 11:49:28
Изменено: RAN — 15.06.2022 11:50:12 |
||
artemkau88 Пользователь Сообщений: 553 |
#7 15.06.2022 11:54:40 Елена Дроздова
, можно еще использовать SQL запрос (добавил в ознакомительных целях)
в ячейку E1 выводит количество строк.
Прикрепленные файлы
|
||||
Jack Famous Пользователь Сообщений: 10852 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
RAN, значит точно не в методах дело, раз ListRows.Count у вас работает — в 1ом сообщении тоже самое UPD: ListObjects — у меня на базе ТСа та же ошибка была — поправил везде Изменено: Jack Famous — 15.06.2022 12:26:27 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
Елена Дроздова Пользователь Сообщений: 106 |
#9 15.06.2022 13:09:05 Сработало вот так:
По-другому никак не работает. |
||
Ігор Гончаренко Пользователь Сообщений: 13746 |
#10 15.06.2022 13:21:46 прямо уж никак))
Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
||
Jack Famous Пользователь Сообщений: 10852 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
#11 15.06.2022 13:28:28
да она явно что-то не то пробовала
если есть итоги, то -2 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
||||
Елена Дроздова Пользователь Сообщений: 106 |
#12 15.06.2022 14:07:43 Вы, скорее всего, правы, но у меня не получалось |
-
How to count rows using VBA?
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. First, you need to define the range for which you want to count the rows.
-
How to count rows with criteria in Excel?
⧪ Then press ALT+F8, select Count_Selected_Rows, and click on Run. You will get a message box showing you the total number of rows in your selected range ( 10 in this case.) 3. Insert VBA Code to Count Rows with Criteria in Excel We can also use a VBA code to count the total number of rows that maintain a specific criterion.
-
How do I get the number of rows in Excel?
Another useful way to get the number of rows is cnt = Worksheets («Sheet2»).Range («A1»).CurrentRegion.Rows.Count. This will get the used range up to the first blank row. I have just provided an example, please don’t stick with the values. you can use any excel range and get the row count. Sheet2 is a sheet, not a range.
-
How to count rows of a range in JavaScript?
We are counting several rows in the RANGE object’s ROWS property, so choose the “COUNT” property now. Now in the message box, show the value of the variable. Now, run the code and see the count of rows of the supplied range of cells. There are 8 rows supplied for the range, so the row count is 8 in the message box.
Grilled Giardiniera-Stuffed Steak Sandwich
This rolled flank steak is inspired by the Italian beef sandwich, a Chicago delicacy typically consisting of chopped thin slices of roast beef stuffed…
Provided by Food Network Kitchen
Mapo Potato
Let’s be clear: Nothing surpasses the hearty deliciousness of a traditional mapo tofu. But for those days when you find yourself without soft tofu in the…
Provided by Hetty McKinnon
Chili
This is a spicy, smoky and hearty pot of chili. It’s the kind of chili you need after a long day skiing — or hibernating. To create a rich and thick sauce,…
Provided by Ali Slagle
Banket
This recipe is from my mother. It is the one she taught me with a slight tweak. In my home on the holidays one way to show someone or a family they were…
Provided by Jena Lewis
Moroccan Nachos
This Moroccan twist on the much-loved appetizer features kefta, a ground beef (or lamb) mixture seasoned with parsley, cilantro, mint, paprika and cumin,…
Provided by Nargisse Benkabbou
Peanut Butter Brownie Cups
I’m not a chocolate fan (atleast not the kind made in the U.S.), but I LOVE peanut butter and chocolate and this hit the spot. I found the recipe in 2007…
Provided by AmyZoe
Banana Cream Pudding
This fabulous version of the favorite Southern dessert boosts the banana flavor by infusing it into the homemade vanilla pudding, in addition to the traditional…
Provided by Martha Stewart
Lemon Russian Tea Cakes
I love lemon desserts,these are a simple cookie I can make quickly. The recipe is based on the pecan Russian tea cakes.I don’t like lemon extract,instead…
Provided by Stephanie L. @nurseladycooks
Easy Churros with Mexican Chocolate Sauce
Forgo the traditional frying — and mixing up the batter! — for this Latin American treat. Instead, bake store-bought puff pastry for churros that are…
Provided by Martha Stewart
Easy Lasagna
Everyone loves lasagna. It’s perfect for feeding a big crowd and a hit at potlucks. But most people reserve it for a weekend cooking project since it can…
Provided by Food Network Kitchen
Grilled Vegetables Korean-Style
Who doesn’t love grilled vegetables — the sauce just takes them over the top.
Provided by Daily Inspiration S @DailyInspiration
Outrageous Chocolate Cookies
From Martha Stewart. I’m putting this here for safe keeping. This is a chocolate cookie with chocolate chunks. Yum! Do not over cook this cookie since…
Provided by C. Taylor
CERTO® Citrus Jelly
A blend of freshly squeezed orange and lemon juices puts the citrusy deliciousness in this CERTO Citrus Jelly.
Provided by My Food and Family
Previous
Next
COUNT ROWS USING VBA IN EXCEL — EXCEL CHAMPS
WebTo 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 …
From excelchamps.com
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 …»>
See details
EXCEL — VBA — RANGE.ROW.COUNT — STACK OVERFLOW
WebSub test () Dim sh As Worksheet Set sh = ThisWorkbook.Sheets («Sheet1») Dim k As Long k = sh.Range («A1», sh.Range («A1»).End (xlDown)).Rows.Count End Sub What happens is this: We count the …
From stackoverflow.com
Sub test () Dim sh As Worksheet Set sh = ThisWorkbook.Sheets («Sheet1») Dim k As Long k = sh.Range («A1», sh.Range («A1»).End (xlDown)).Rows.Count End Sub What happens is this: We count the …»>
See details
VBA ROW COUNT — HOW TO COUNT NUMBER OF USED ROWS IN VBA?
2023-03-20
From wallstreetmojo.com
Estimated Reading Time 4 mins
HOW TO COUNT UNIQUE VALUES IN RANGE USING VBA — STATOLOGY
WebMar 14, 2023 You can use the following basic syntax to count the number of unique values in a range using VBA: Sub CountUnique () Dim Rng As Range, List As Object, …
From statology.org
Mar 14, 2023 You can use the following basic syntax to count the number of unique values in a range using VBA: Sub CountUnique () Dim Rng As Range, List As Object, …»>
See details
在 VBA 中查找最后一行和最后一列_迹忆客
WebMar 19, 2023 在 VBA 中查找最后一行和最后一列. 在处理电子表格中的数据时,我们需要知道数据的最后一行和最后一列。. 设置光标可以迭代的限制很有用。. VBA 没有内置函数 …
From jiyik.com
Mar 19, 2023 在 VBA 中查找最后一行和最后一列. 在处理电子表格中的数据时,我们需要知道数据的最后一行和最后一列。. 设置光标可以迭代的限制很有用。. VBA 没有内置函数 …»>
See details
VBA : HOW TO COUNT NUMBER OF ROWS IN FILTERED COLUMN?
WebAug 19, 2015 Here is the code used to apply auto filter: Sub filtered_row_count () Sheets («Sheet1»).Select row_count = Application.CountA (Range («B:B»)) — 1 ‘Subtract the …
From stackoverflow.com
Aug 19, 2015 Here is the code used to apply auto filter: Sub filtered_row_count () Sheets («Sheet1»).Select row_count = Application.CountA (Range («B:B»)) — 1 ‘Subtract the …»>
See details
HOW TO COUNT ROWS WITH DATA IN COLUMN USING VBA IN EXCEL (9 …
WebFeb 16, 2023 Method-1: Using VBA Rows.Count Property to Count Rows with Data in Column in Excel Here, we will be counting the rows of the Sales column with sales …
From exceldemy.com
Feb 16, 2023 Method-1: Using VBA Rows.Count Property to Count Rows with Data in Column in Excel Here, we will be counting the rows of the Sales column with sales …»>
See details
EXCEL FILE TO COUNT TOTAL ROWS IN VBA — STACK OVERFLOW
WebMay 9, 2012 Try the followings: To get the count of used rows: cnt = Worksheets («Sheet2»).Cells.SpecialCells (xlCellTypeLastCell).Row To get the count of all rows of …
From stackoverflow.com
May 9, 2012 Try the followings: To get the count of used rows: cnt = Worksheets («Sheet2»).Cells.SpecialCells (xlCellTypeLastCell).Row To get the count of all rows of …»>
See details
COUNT THE NUMBER OF ROWS OR COLUMNS IN EXCEL — MICROSOFT SUPPORT
WebIf you need a quick way to count rows that contain data, select all the cells in the first column of that data (it may not be column A). Just click the column header. The status …
From support.microsoft.com
If you need a quick way to count rows that contain data, select all the cells in the first column of that data (it may not be column A). Just click the column header. The status …»>
See details
VBA COUNT — AUTOMATE EXCEL
WebUsing COUNTA. The count will only count the VALUES in cells, it will not count the cell if the cell has text in it. To count the cells which are populated with any sort of data, we …
From automateexcel.com
Using COUNTA. The count will only count the VALUES in cells, it will not count the cell if the cell has text in it. To count the cells which are populated with any sort of data, we …»>
See details
RANGE.ROWS PROPERTY (EXCEL) | MICROSOFT LEARN
WebMar 29, 2022 For example, both Selection.Rows(1) and Selection.Rows.Item(1) return the first row of the selection. When applied to a Range object that is a multiple selection, this …
From learn.microsoft.com
Mar 29, 2022 For example, both Selection.Rows(1) and Selection.Rows.Item(1) return the first row of the selection. When applied to a Range object that is a multiple selection, this …»>
See details
VBA: HOW TO COUNT NUMBER OF ROWS IN RANGE — STATOLOGY
WebMar 9, 2023 VBA: How to Count Number of Rows in Range You can use the following basic syntax to count the number of rows in a range in Excel using VBA: Sub …
From statology.org
Mar 9, 2023 VBA: How to Count Number of Rows in Range You can use the following basic syntax to count the number of rows in a range in Excel using VBA: Sub …»>
See details
COUNT THE ROWS IN A SELECTION — VBA CODE EXAMPLES — AUTOMATE …
WebIn this ArticleCount Rows in a SelectionCount Columns in a SelectionVBA Coding Made Easy If you ever need to count the number of rows that were selected, use …
From automateexcel.com
In this ArticleCount Rows in a SelectionCount Columns in a SelectionVBA Coding Made Easy If you ever need to count the number of rows that were selected, use …»>
See details
[EXCEL VBA] COUNT COLUMNS & ROWS HAVING DATA (10 EDITABLE CODES)
WebMay 18, 2022 This code will count all the columns in a given range mentioned in the code. This code counts all the blank as well as non-blank columns within the specified range. …
From excelgraduate.com
May 18, 2022 This code will count all the columns in a given range mentioned in the code. This code counts all the blank as well as non-blank columns within the specified range. …»>
See details
HOW TO GET THE ROW COUNT IN EXCEL VBA — STACK OVERFLOW
WebJul 9, 2018 You can assign the return value to a variable like this: lastRow = Sheets (1).UsedRange.Rows.Count If you use a function that includes a column (such as column A) as shown in other examples, that will only get you the count of rows in that column, …
From stackoverflow.com
Jul 9, 2018 You can assign the return value to a variable like this: lastRow = Sheets (1).UsedRange.Rows.Count If you use a function that includes a column (such as column A) as shown in other examples, that will only get you the count of rows in that column, …»>
See details
HOW TO PROPERLY COUNT VISIBLE ROWS IN VBA EXCEL?
WebJan 25, 2021 Option Explicit Dim ws As Worksheet Dim rCount As Long, x As Long Dim rng As Range Sub printTest () Dim content As String Set ws = …
From stackoverflow.com
Jan 25, 2021 Option Explicit Dim ws As Worksheet Dim rCount As Long, x As Long Dim rng As Range Sub printTest () Dim content As String Set ws = …»>
See details
HOW TO COUNT ROWS WITH VBA IN EXCEL (5 APPROACHES)
WebFeb 16, 2023 Use VBA Code to Count Rows of a Specific Range ⧪ Step 1: Press ALT+F11 on your keyboard. The VBA window will open. ⧪ Step 2: Go to the Insert tab in …
From exceldemy.com
Feb 16, 2023 Use VBA Code to Count Rows of a Specific Range ⧪ Step 1: Press ALT+F11 on your keyboard. The VBA window will open. ⧪ Step 2: Go to the Insert tab in …»>
See details
EXCEL VBA TO COUNT ROWS WITH DATA (4 EXAMPLES)
WebFeb 19, 2023 After the VBA window appears, write the following codes in it- Sub CountUsedRows () Dim x As Long x = Selection.Rows.Count MsgBox x & » rows with …
From exceldemy.com
Feb 19, 2023 After the VBA window appears, write the following codes in it- Sub CountUsedRows () Dim x As Long x = Selection.Rows.Count MsgBox x & » rows with …»>
See details
VBA USED RANGE – COUNT NUMBER OF USED ROWS OR COLUMNS
WebThere is no need to loop to find this, the following code does it for you. In this example the code will write “FirstEmpty” in the first empty cell in column “d”. Public Sub AfterLast () …
From automateexcel.com
There is no need to loop to find this, the following code does it for you. In this example the code will write “FirstEmpty” in the first empty cell in column “d”. Public Sub AfterLast () …»>
See details
HOW TO COUNT FILTERED ROWS IN EXCEL WITH VBA (STEP-BY-STEP
WebFeb 13, 2023 Steps to Count Filtered Rows in Excel with VBA STEP 1: Apply Filter in the Dataset STEP 2: Launch the VBA Window to Count Filtered Rows in Excel STEP 3: …
From exceldemy.com
Feb 13, 2023 Steps to Count Filtered Rows in Excel with VBA STEP 1: Apply Filter in the Dataset STEP 2: Launch the VBA Window to Count Filtered Rows in Excel STEP 3: …»>
See details
5 / 5 / 0 Регистрация: 21.09.2012 Сообщений: 37 |
|
1 |
|
Количество строк на листе или номер последней строки с данными07.03.2014, 00:34. Показов 12406. Ответов 6
Как получить количество строк на листе или номер последней строки с данными?
0 |
Sasha_Smirnov 5561 / 1367 / 150 Регистрация: 08.02.2009 Сообщений: 4,107 Записей в блоге: 30 |
||||
07.03.2014, 03:45 |
2 |
|||
Нажатием сочетания клавиш Ctrl-End. Буквально за 1 секунд записал макрос (строка 3):
1 |
5 / 5 / 0 Регистрация: 21.09.2012 Сообщений: 37 |
|
07.03.2014, 15:41 [ТС] |
5 |
По второй ссылке много правды. Что Вам помешало её добиться? Спасибо! Буду разбираться.
0 |
5561 / 1367 / 150 Регистрация: 08.02.2009 Сообщений: 4,107 Записей в блоге: 30 |
|
08.03.2014, 19:51 |
6 |
ActiveCell.SpecialCells(xlLastCell).row
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
08.03.2014, 21:22 |
7 |
ActiveCell.SpecialCells(xlLastCell).Row — это не последняя строка с данными. Это последняя когда-то использованная строка, причём если она скрыта — то выводится номер ближайшей видимой строки выше. В общем, без примера листа и озвучивания всей задачи 100% корректно не ответить.
2 |