从Excel中获取文件夹路径,以计算Excel VBA中该文件夹内的文件

时间:2016-12-22 09:17:50

标签: excel vba excel-vba macros

我有以下代码,它返回文件夹中的文件数。

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工作表中的输入,以便我在单元格A1中输入文件夹路径并获取B1中的文件数。我是Excel Macros的新手 - 如果这是非常基本的话,请原谅。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

您可以通过以下方式从单元格A1发送folderPath字符串:

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

将文件夹路径放在单元格A1中并运行宏。

你将获得B1细胞计数

修改

用于循环遍历A1,A2,A3 ......列中填写的所有文件夹路径,并在相应的单元格中获取计数,即B1,B2,B3 ......如下所示:

获取已填充文件夹路径的总行数

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

答案 1 :(得分:0)

考虑到您的宏工作正常,您需要做的就是以这种方式将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中根据需要执行操作并键入A1文件夹路径和B1 =FileCounter(A1)

请注意,您获得的文件数量仅为.xls,但不包括.xlsx.xlsm和其他人。要在结果中包含所有Excel文件,您需要将扩展​​模式更改为\*.xls*