从工作表中获取文件夹path以计算Excel VBA中该文件夹内的文件
我有下面的代码,它返回文件夹中的文件数量。
Sub sample() Dim FolderPath As String, path As String, count As Integer FolderPath = "C:\Documents and Settings\Santosh\Desktop" path = FolderPath & "\*.xls" Filename = Dir(path) Do While Filename <> "" count = count + 1 Filename = Dir() Loop Range("Q8").Value = count 'MsgBox count & " : files found in folder" End Sub
我需要参数化FolderPath
作为Excel工作表本身的input,以便在单元格A1中input文件夹path并获取B1中的文件号。 我很新的Excelmacros – 如果这是非常基本的借口。 我怎样才能做到这一点?
您可以通过以下方式从单元格A1发送folderPathstring:
Sub sample() Dim FolderPath As String, path As String, count As Integer FolderPath = Range("A1") path = FolderPath & "\*.xls" Filename = Dir(path) Do While Filename <> "" count = count + 1 Filename = Dir() Loop Range("B1").Value = count MsgBox count & " : files found in folder" End Sub
将您的文件夹path放在单元格A1中并运行macros。
你会在B1单元格计数
编辑
为了遍历在A1,A2,A3 …列中填充的所有文件夹path,并在相应的单元格B1,B2,B3中进行计数,请执行以下操作:
获取已填充文件夹path的总行数
TotalRows = Range("A" & Rows.count).End(xlUp).Row
然后从1循环到完整的行填入列A.
Sub sample() Dim FolderPath As String, path As String, count As Integer Dim TotalRows As Integer TotalRows = Range("A" & Rows.count).End(xlUp).Row For i = 1 To TotalRows count = 0 FolderPath = Range("A" & i) path = FolderPath & "\*.xls" Filename = Dir(path) Do While Filename <> "" count = count + 1 Filename = Dir() Loop Range("B" & i).Value = count 'MsgBox count & " : files found in folder" Next i End Sub
考虑到你的macros工作正常,所有你需要做的就是以这种方式将你的Sub
转换成Function
:
Function FileCounter(FolderPath as String) Dim path As String, count As Integer path = FolderPath & "\*.xls" Filename = Dir(path) Do While Filename <> "" count = count + 1 Filename = Dir() Loop FileCounter = count End Function
接下来,在Excel中根据需要inputA1文件夹path,并在B1 =FileCounter(A1)
请注意,只有.xls
扩展名的文件数量不是.xlsx
, .xlsm
和其他文件。 要将所有Excel文件包含在结果中,您需要将扩展模板更改为\*.xls*
。