Excel计数子文件夹错误的文件夹中的文件

它适用于单个文件夹,但是如果treee级别高于2,错误会随着树的长度而增加。

我正在试图获取包括子文件夹在内的xl的数量,以便创build一个数组。

(我将使用打开另一个子文件中的所有文件并创build一个报告)

有任何想法吗?

Private Sub Countfiles(FF As Scripting.Folder) Dim F As Scripting.file Dim SubF As Scripting.Folder Dim k As Integer For Each F In FF.Files If F.Path Like "*.xl*" Then k = k + 1 Debug.Print r_tot + k Else End If Next For Each SubF In FF.Subfolders r_tot = r_tot + k Countfiles SubF Next SubF End Sub 

使用下面的代码片段获取文件数(Exceltypes.xls)在一个文件夹中。 将其应用到所有感兴趣的文件夹,并将计数添加到累加器var。

 Function FilesCount(FolderPath) Dim FolderPath As String, path As String, count As Integer path = FolderPath & "\*.xls" Filename = Dir(path) Do While Filename <> "" count = count + 1 Filename = Dir() Loop FilesCount=count End Sub 

希望这会有所帮助。 RGDS,

另一种方法是通过VBA使用PowerShell – 单行就足以recursion计算文件和文件夹(或转储完整的列表)。

下面的代码是使用FSODIRrecursion循环方面的一个很大的改进,但是与从文件夹C:\temp直接使用PowerShell的简单性相比,令人沮丧地长:

Write-Host ( Get-ChildItem c:\temp -recurse -include *.xls* | Measure-Object | export-csv C:\temp\filename.csv

  • 更改strFolder以设置文件和文件夹计数的感兴趣的文件夹

 Sub BYpass() Dim strFolder As String Dim StrIn As String Dim WB As Workbook Dim X1 Dim X2 strFolder = "c:\temp" StrIn = "C:\temp\filename.csv" 'export file count X1 = Shell("powershell.exe Write-Host ( Get-ChildItem " & strFolder & " -recurse -include *.xls* | Measure-Object | export-csv " & StrIn & ")", 1) 'export detail of all files X2 = Shell("powershell.exe Write-Host ( Get-ChildItem " & strFolder & " -recurse -include *.xls* | export-csv " & StrIn & ")", 1) Set WB = Workbooks.Open(StrIn) End Sub 

循环的每次迭代都有它自己的k实例,而不是将它的值返回给调用例程

您可以将计数作为参数添加到Sub

 Private Sub Countfiles(FF As Scripting.Folder, ByRef count As Long) Dim f As Scripting.file Dim SubF As Scripting.Folder For Each f In FF.Files If f.Path Like "*.xl*" Then count = count + 1 End If Next For Each SubF In FF.Subfolders Countfiles SubF, count Next SubF End Sub 

或将其转换为Function

 Function fCountfiles(FF As Scripting.Folder) As Long Dim count As Long Dim f As Scripting.file Dim SubF As Scripting.Folder For Each f In FF.Files If f.Path Like "*.xl*" Then count = count + 1 End If Next For Each SubF In FF.Subfolders count = count + fCountfiles(SubF) Next SubF fCountfiles = count End Function