Đếm số lượng tệp files trong thư mục và thư mục con với VBA
Bước 1:
Copy code VBA sau đây vào 1 Module mới trong VBA:
Function fCount(strPath) | |
Dim fCnt As Integer | |
fCnt = ShowFolderList(strPath) | |
fCount = fCnt | |
End Function | |
Sub CntFiles() | |
Dim strPath As String | |
strPath = "A:\Asif\Answers\abc" | |
ShowFolderList (strPath) | |
End Sub | |
Function ShowFolderList(Path) | |
Dim fso, folder, subFlds, fld | |
Dim tFiles As Integer | |
tFiles = ShowFilesList(Path) | |
Set fso = CreateObject("Scripting.FileSystemObject") | |
Set folder = fso.GetFolder(Path) | |
Set subFlds = folder.SubFolders | |
For Each fld In subFlds | |
If fld.Name = "Entered" Then | |
GoTo SkipFld: | |
Else | |
Path = fld.Path | |
tFiles = tFiles + ShowFilesList(Path) | |
End If | |
SkipFld: | |
Next | |
'MsgBox tFiles & " files" | |
ShowFolderList = tFiles | |
End Function | |
Function ShowFilesList(folderspec) | |
Dim fso, f, f1, fc, s | |
Dim Cnt As Integer | |
Set fso = CreateObject("Scripting.FileSystemObject") | |
Set f = fso.GetFolder(folderspec) | |
Set fc = f.Files | |
ShowFilesList = fc.Count | |
End Function |
view raw getFilesCount.bas hosted with ❤ by GitHub
View the code on Gist.
Cách sử dụng:
trong 1 ô trên Excel: sử dụng công thức
A1 = fCount(“<đường dẫn đến thư mục cần đếm files”)
Xem ngay: Tài hiệu hướng dẫn sử dụng excel 2007 toàn tập
Bước 1: Copy code này vào trong 1 Module
Function CountFilesInFolder(strDir As String, Optional strType As String) | |
Dim file As Variant, i As Integer | |
If Left(strDir, 1) <> "\" Then strDir = strDir & "\" | |
file = Dir(strDir & strType) | |
While (file <> "") | |
i = i + 1 | |
file = Dir | |
Wend | |
CountFilesInFolder = i | |
End Function |
view raw CountFilesInFolder.bas hosted with ❤ by GitHub
View the code on Gist.
Bước 2: Cách sử dụng trên Excel: xem hình vẽ. Lưu ý, Function chỉ đếm, thống kê số lượng file trong 1 thư mục, không đếm trong cả các thư mục con
đếm số lượng file trong một thư mục
Khóa học liên quan