简体   繁体   中英

Count number of rows in multiple Excel sheets and return values to a “summary” sheet

I have an Excel workbook with 10 plus sheets.

On the "Summary" sheet I want to summarise how many rows are used on each of the other sheets.

I'm thinking that a Function that gets called multiple times is the most efficient.

If this is so, then I think it starts something like;

Function CountMyRows(SName)  # where SName is the name of a sheet
    Dim rowCount As Integer
    rowCount = Worksheets("SName").Rows.Count

Am I starting in the right direction?

I want to summarise how many rows are used on each of the other sheets

you're looking for UsedRange property:

Function CountMyRows(SName As String) As Long
    CountMyRows = ThisWorkbook.Worksheets(SName).UsedRange.Rows.Count
End Function

note, that I'm using Worksheets(SName) without quotes and also it's more reliable to use Long type for storing rows count, because max value of Integer is only 32767 .

在此处输入图片说明

List Your sheets (names) in A1-Axx , in column B (eg cell B1 ) enter a formula:

=COUNTA(INDIRECT(A1&"!A:A"))

In example below I added "-1" to not to count header row in sheets.


1

Place the following two Functions into a module in the Workbook where you want to count the used rows in all worksheets. I used Function 'Test_it' to grab every sheet in the workbook, then call 'CountMyRows' by passing a Sheet name. To test it, place the cursor inside the 'Test_It' function, then press F5. You will see the results in the immediate window.

Note your code had to be changed because (1) it counted total rows in sheet - not used rows; and (2) an Integer may be too small ...

Function Test_It()
    For Each Sheet In ThisWorkbook.Sheets
        Debug.Print Sheet.Name & vbTab & CountMyRows(Sheet.Name)
    Next Sheet
End Function


Function CountMyRows(SName) As Long         '# where SName is the name of a sheet
    Dim rowCount As Long
    rowCount = Worksheets(SName).UsedRange.Rows.Count
    CountMyRows = rowCount
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM