count how many of files in each folder and subfold

2020-06-29 01:48发布

I have obtained the filename and corresponding folder in column a and b.

How Can I count the number of files in each folder and subfolder?

these are the references:

count files in specific folder and display the number into 1 cel

http://software-solutions-online.com/excel-vba-find-and-list-all-files-in-a-directory-and-its-subdirectories/

I have done the following so far

Private Sub SelectFolder_Click()
Call GetAllFolders(x, strPath, objFso, intCountRows)
Call count
End Sub

The following is the counting part

Sub count()
Dim FolderPath As String, path As String, count As Integer
Dim Filename As String
Dim strPath As String

FolderPath = "D:\Users\Desktop\test"

Filename = Dir("")

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

Range("C3").Value = count
'MsgBox count & " : files found in folder"
End Sub

How Can I count the number of files in each folder and subfolder? Thanks

标签: excel vba
1条回答
萌系小妹纸
2楼-- · 2020-06-29 02:38

GetFileCount will count all the files in a directory and the directory's sub-directories.

Range("C3").Value = getFileCount("D:\Users\Desktop\test")

Function getFileCount(localRoot, Optional fld, Optional count As Long) As Long
    Dim fso, f, baseFolder, subFolder, ftpFile, i

    Set fso = CreateObject("Scripting.Filesystemobject")

    If IsMissing(fld) Then
        Set baseFolder = fso.GetFolder(localRoot)
    Else
        Set baseFolder = fld
    End If

    count = count + baseFolder.Files.count

    For Each subFolder In baseFolder.SubFolders
        getFileCount localRoot, subFolder, count
    Next

    getFileCount = count
End Function
查看更多
登录 后发表回答