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

ⅰ亾dé卋堺 提交于 2020-01-03 05:46:09

问题


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?


回答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



回答2:


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.



来源:https://stackoverflow.com/questions/22694463/count-number-of-rows-in-multiple-excel-sheets-and-return-values-to-a-summary-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!