计算文件夹中的* .pdf文件并更新电子表格中的相邻列

时间:2016-07-04 22:27:42

标签: excel vba pdf

enter image description here

我有以下excel电子表格,tracker.xls有2列:category和count。

我想遍历一个子目录,该子目录包含与我的电子表格中的类别列匹配的pdf文件。

enter image description here

这是我到目前为止所做的,但我的代码似乎没有起作用:

Sub CV()

    Function CVCount()

        CategoryArray = Range("A2:A3")
        CountArray = Range("B2:B3")

        For i = 1 To UBound(CategoryArray)

            For j = 1 To UBound(CategoryArray, 2)

            'get name of category

            Dim Category As String
            Category = (myarray(i, j))
            FolderPath = Category + "\"
            path = FolderPath & "\*.pdf"
            Filename = Dir(path)

                For k = 1 To UBound(CountArray)

                    For l = 1 To UBound(CountArray, 2)

                        'get count

                        Do While Filename <> ""
                            count = count + 1
                            Filename = Dir()
                        Loop

                        'assign count to cell
                        Range("").Value = count

                Next k

            Next j

        Next i

    End Function

End Sub

我似乎无法弄清楚如何为细胞分配计数。任何想法如何?

1 个答案:

答案 0 :(得分:1)

你走在正确的轨道上,但它比那简单得多:

    Option Explicit

Private Const baseFolder As String = "C:\Users\Hazel\Documents\Personal\Accounts\Childcare\"

 Sub countFiles()

    Dim path As String
    Dim fileName As Variant
    Dim count As Integer
    Dim i As Integer

    i = 1

    Do While Range("A" & i + 1).Value <> ""

        count = 0

        i = i + 1
        path = baseFolder & Range("A" & i).Value & "\"

        fileName = Dir(path)

        Do While fileName <> ""

            If UCase$(Right(fileName, 3)) = "PDF" Then count = count + 1
            fileName = Dir()

        Loop

        Range("B" & i).Value = count

    Loop

End Sub

只需更改“baseFolder”常量即可匹配起始目录。