它适用于单个文件夹,但如果树级别高于2,则错误会随着树的长度而增加。
我正在尝试在包含子文件夹的文件夹中获取 xl 的数量,以便创建数组。
(我将使用打开另一个子中的所有文件并创建报告)
有什么想法吗?
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
答案 0 :(得分:0)
使用以下代码段在单个文件夹中获取(Excel类型.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,
答案 1 :(得分:0)
循环的每次迭代都有它自己的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
答案 2 :(得分:0)
另一种方法是通过PowerShell
使用VBA
- 单行足以递归计算文件和文件夹(或转储相同的完整列表)。
下面的代码是对使用 FSO 或 DIR 的递归循环的一个很大的改进,但与直接使用PowerShell
的简单性相比,令人沮丧的长来自文件夹C:\temp
只是:
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