excel - 每张 Excel 行数
问题描述
我目前正在使用下面的代码来计算每张工作表中的所有行,并打印在工作簿的主工作表上。现在,我正在尝试在该特定工作表的最后一行以及主工作表上打印每个工作表上使用的行数。
Function Test_It()
Dim printRow As Integer
printRow = 2
For Each Sheet In ThisWorkbook.Sheets
Range("N" & printRow).Value = "Sheet Name:"
Range("O" & printRow).Value = Sheet.Name
Range("P" & printRow).Value = "Count:"
Range("Q" & printRow).Value = CountMyRows(Sheet.Name)
printRow = printRow + 1
Next Sheet
End Function
Function CountMyRows(SName As String) As Long '# where SName is the name of a sheet
Dim RowCount As Long
RowCount = ThisWorkbook.Worksheets(SName).UsedRange.Rows.Count - 1
CountMyRows = RowCount
End Function
任何帮助表示赞赏,在此先感谢!
无效的代码
Sub LineCount()
Dim ws As Worksheet
Dim RowCount As Integer
Dim countTotal As Long
Dim myArray() As Variant
RowCount= ActiveWorkbook.Worksheets.Count
countTotal = RowCount
ReDim myArray(1 To RowCount)
For i = 1 To RowCount
countTotal = ""
myArray(1) = Worksheets(i).UsedRange.Rows.Count
Debug.Print myArray(1)
Range("A" & countTotal).Value = countTotal
Next
End Sub
这是目标:
主表:
表 2:
表 3:
表 4:
我开始工作的最终代码
Sub LineCount()
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
For Each sht In ThisWorkbook.Worksheets
dict(sht.Name) = sht.Cells(sht.Rows.Count, 1).End(xlUp).Row
sht.Range("A" & Rows.Count).End(xlUp).Offset(2, 0) = "Rows Used: " & dict(sht.Name)
Next sht
With Sheet1
.Range("A1").Resize(dict.Count).Value = Application.Transpose(dict.Keys)
.Range("B1").Resize(dict.Count).Value = Application.Transpose(dict.Items)
End With
End Sub
现在唯一的问题是,当多次按下按钮时,它会将行数从 14 行重新计算到现在的 28 行,依此类推(取决于按下按钮的次数)。如何解决?
解决方案
一些相当基本的东西可能是:
Sub Test()
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
For Each sht In ThisWorkbook.Worksheets
dict(sht.Name) = sht.Cells(sht.Rows.Count, 1).End(xlUp).Row
Next sht
With Sheet1
.Range("A2").Resize(dict.Count).Value = Application.Transpose(dict.Keys)
.Range("B2").Resize(dict.Count).Value = Application.Transpose(dict.Items)
End With
End Sub
如果您想避免包含“主”表,请在属性上实施If
条件,无论您的情况是什么。sht.Name
推荐阅读
- react-native - react-native 中的应用程序状态不会删除侦听器
- java - 为什么绘画类不适用于 setDefaultLookAndFeelDecorated(true)
- icons - 如何根据 web 的新主题使用大纲物化图标?
- vuejs2 - Vue(类似)组件和可重用性
- reactjs - 如何在没有 Create-react-app 的情况下创建 React App
- javascript - 在 JSX 中返回多个元素
- html - 在非常大的表格右侧添加边距(溢出文档)
- javascript - 从jquery添加图像到光滑
- c# - 从 2 张桌子上带孩子
- apache-spark - 更改“spark.memory.storageFraction”对“执行程序”选项卡中的“存储内存”列没有影响