如何计算VBA中子文件夹的工作簿中的行数?

我试图从一些文件夹和子文件夹中统计文件的行数。 文件夹和子文件夹path被写入G列。

Sub CountRows() Dim wbSource As Workbook, wbDest As Workbook Dim wsSource As Worksheet, wsDest As Worksheet Dim strFolder As String, strFile As String Dim lngNextRow As Long, lngRowCount As Long Dim LastRow Dim cl As Range Application.ScreenUpdating = False Set wbDest = ActiveWorkbook Set wsDest = wbDest.ActiveSheet LastRow = wsDest.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row For Each cl In wsDest.Range("G11:G" & LastRow) strFolder = cl.Value strFile = Dir(strFolder & "/") lngNextRow = 11 Do While Len(strFile) > 0 Set wbSource = Workbooks.Open(Filename:=strFolder & "/" & strFile) Set wsSource = wbSource.Worksheets(1) lngRowCount = wsSource.UsedRange.Rows.Count wsDest.Cells(lngNextRow, "F").Value = lngRowCount - 1 wbSource.Close savechanges:=False lngNextRow = lngNextRow + 1 strFile = Dir Loop Next cl ... 

结果必须插入F列。也许有人可以解释一下,这个循环出了什么问题,因为每个文件中的行数在目录F中重复在F列。

例如,如果我有一个文件夹有3个文件,在GI列将有3个目录(从3个文件C:\用户\桌面\ vba_files \等每个目录1),那么我会得到F列3个数字是来自文件夹C:\ Users \ Desktop \ vba_files \的每个工作簿中的行数,但每个计数重复3次(按目录数)。

它看起来如下:

在这里输入图像说明

代码中的逻辑存在问题。 从G列开始,每个文件都包含一个条目,因此对于具有3个文件的文件夹,有3个重复行。 但是Do While循环会为当前目录中的每个文件返回一个长度(因为您继续不带参数地调用Dir )。 然后For Each循环移动到G列中的下一个单元格,该单元格再次包含相同的目录, Do While循环再次启动,并在F列中获得另外3个条目。

我不知道你为什么要从G列开始重复这些操作,但是如果你这样做了,那么你只需要一个循环来遍历列G中的每个单元格,然后检查目录是否每次都改变。 下面的代码是这样的:

 Sub CountRows() Dim wbSource As Workbook, wbDest As Workbook Dim wsSource As Worksheet, wsDest As Worksheet Dim strFolder As String, strFile As String Dim lngNextRow As Long, lngRowCount As Long Dim LastRow Dim cl As Range 'Application.ScreenUpdating = False Set wbDest = ActiveWorkbook Set wsDest = wbDest.ActiveSheet LastRow = wsDest.Cells(wsDest.rows.count,7).end(xlUp).Row lngNextRow = 11 strFolder = "" For Each cl In wsDest.Range("G11:G" & LastRow) If cl.Value <> strFolder Then strFolder = cl.Value strFile = Dir(strFolder & "/*.xl*") Else strFile = Dir End If If Len(strFile) > 0 Then Set wbSource = Workbooks.Open(Filename:=strFolder & "/" & strFile) Set wsSource = wbSource.Worksheets(1) lngRowCount = wsSource.UsedRange.Rows.Count wsDest.Cells(lngNextRow, "F").Value = lngRowCount - 1 wbSource.Close savechanges:=False lngNextRow = lngNextRow + 1 End If Next cl End Sub 

请注意,如果目录中的文件数量大于列G中相应条目的数量,那么额外的文件将被忽略。

我第一次调用Dir()来添加一个filter来只拾取Excel文件。 我也改变了LastRow的计算方式,以一种更安全的方式(如果下面有任何数据,并且在G中最后一个单元的右边,你的代码会给出错误的结果)。

实现这样的一个更好的方式可能是:

  • 只需要input一个没有重复的目录列表
  • 循环input
  • 对于每个input单元格,输出所有文件并在单独的输出表单上进行计数

那么你可以拿起,但是每个文件夹中有很多文件,而不必获取列G中的条目数量。