【问题标题】:Get folder path from sheet to count files inside that folder in Excel VBA获取工作表中的文件夹路径以计算 Excel VBA 中该文件夹内的文件
【发布时间】:2017-05-07 20:48:58
【问题描述】:

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

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 宏很陌生 - 如果这是非常基本的,请原谅。我该怎么做?

【问题讨论】:

    标签: vba excel macros


    【解决方案1】:

    您可以通过以下方式从单元格 A1 发送文件夹路径字符串:

    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...

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

    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
    

    【讨论】:

    • 非常感谢 - 这有效。万一我需要在A列中填写多个文件夹路径,并在B列中一次性获取相应数量的文件?我在哪里更改它?
    • 查看 A 中多个文件夹路径的已编辑答案并计入 B 列。@SriramIlango
    【解决方案2】:

    考虑到您的宏运行良好,您只需将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*

    【讨论】:

      猜你喜欢
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 2017-07-07
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多