我想用Excel VBA统计文件夹中的文件数。
现在速度对我来说非常重要,所以首先我将所有文件(从文件夹和子文件夹)列出到“A”列,然后我想遍历所有行并计算文件夹中有多少个文件。
“A”列中的我的列表:
D:\Steam\libraryfolder.vdf
D:\Steam\steam.dll
D:\Steam\config\appconfig.json
D:\Steam\config\chaperone_info.vrchap
D:\Steam\config\steamvr.vrsettings
D:\Steam\config\lighthouse\lighthousedb.json
D:\Steam\config\lighthouse\lhr-eebe0f79\config.json
D:\Steam\config\lighthouse\lhr-eebe0f79\userdata\Green_46GA163X002581_mura_analyzes.mc
D:\Steam\config\lighthouse\lhr-eebe0f79\userdata\Green_46HA163P000228_mura_analyzes.mc
我想获取“B”列的文件数量。 因此“B”列应如下所示:
2
2
3
3
3
1
1
2
2
目前我有这个小代码,用于计算“”,但不幸的是我不知道如何计算文件。
Sub test()
Dim S As String
S = "D:\Steam\config\lighthouse\lhr-eebe0f79\config.json"
MsgBox "count = " & UBound(Split(S, "\"))
End Sub
最佳答案
您不需要为此使用 VBA,标准 Excel 函数可以计算这些计数。
B 列用于从路径中提取文件名:
=MID(A1,FIND("*",SUBSTITUTE(A1,"\","*",LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))+1,LEN(A1))
然后使用 C 列提取路径:
=LEFT(A1,LEN(A1)-LEN(B1))
最后,D 列可以计算驻留在同一目录中的文件数量:
=COUNTIF(C:C,$C1)
如果您确实需要在 VBA 中执行此操作,那么这里有几个函数可以提取给定完整路径的文件名或目录:
' Returns the file name given a full file path
Function BaseName(FilePath)
BaseName = Mid(FilePath, InStrRev(FilePath, "\") + 1)
End Function
' Returns the directory path given a full file path
Function DirName(FilePath)
DirName = Mid(FilePath, 1, Len(FilePath) - Len(BaseName(FilePath)))
End Function
关于excel - 如何统计文件夹中的文件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71422694/