我有以下脚本。想要文件夹、子文件夹和文件的数量:
Sub CountFiles(ByVal path1 As String)
Dim fso As Object
Dim subfolder As Object
Dim file As Object
Dim folder As Object
Dim stetje As Long
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(path1)
For Each subfolder In folder.SubFolders
CountFiles (subfolder.path)
Next subfolder
For Each file In folder.Files
Range("A" & Rows.Count).End(xlUp).Offset(1, 0) = file.path
Next file
Set fso = Nothing
Set folder = Nothing
Set subfolder = Nothing
Set file = Nothing
End Sub
你称之为:
Sub someStuff()
Call CountFiles ("c:/temp/test/")
End Sub
此脚本将所有文件夹、子文件夹和文件的路径写入 Excel 单元格
但我真正想要的是计算所有的出现的总到一个变量。
所以而不是这个:
For Each file In folder.Files
Range("A" & Rows.Count).End(xlUp).Offset(1, 0) = file.path
Next file
我想要这样的东西:
For Each file In folder.Files
number = number + file.path.Count // of course this line is completely pseudo
Next file
所以想要的输出是例如数字:2345 而不是 2345 行,并写出路径。
任何帮助/提示将不胜感激!
这是一种方法:
Function CountFiles(ByVal path As String) As Long
Dim fso As Object
Dim folder As Object
Dim subfolder As Object
Dim amount As Long
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(path)
For Each subfolder In folder.SubFolders
amount = amount + CountFiles(subfolder.path)
Next subfolder
amount = amount + folder.Files.Count
Set fso = Nothing
Set folder = Nothing
Set subfolder = Nothing
CountFiles = amount
End Function
Sub someStuff()
MsgBox CountFiles("c:/temp/test/")
End Sub
我已经把 sub 变成了一个函数,它返回在该文件夹和子文件夹中找到的文件数量。和以前一样,这是递归的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句