excel - 如何统计文件夹中的文件数

标签 excel vba file count

我想用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/

相关文章:

python - Django:检查图像是否存在于某个特定的 url

Delphi - 获取应用程序打开了哪些文件

vba - CDate() 的行为不一致

excel - 创建一个 Excel 宏以跨可变/未知数量的列复制公式?

c++ - 自动生成的文件和 VC++ 2008 项目

excel - 如何使用 "WorksheetFunction.Match"作为具有可变范围的数组

vba - 在 MSWord 表的第一列中创建书签

Excel 筛选公式/函数 - 从筛选公式/函数返回第一行

c# - 如何在 asp.net 中将 RDLC 报告导出为 .xlsx 格式?

excel - 有没有办法查看一个单元格是否在公式中使用并用条件格式标记它