Public Sub ListFilesOrFolders(ByVal FolderStart As String, result, Optional sFilter As String = "", _
Optional folder As Boolean = False, Optional inSub As Boolean = False, Optional NameOnly As Boolean = True)
' Neu lay tat ca cac tap tin hoac thu muc thi nhap sFilter = "" (da la mac dinh nen co the bo qua)
' Neu lay tat ca cac tap tin vd. co dang JPG thi sFilter = "*.jpg",
' Neu lay tat ca cac tap tin JPG ma ten phai chua hichic thi sFilter = "*hichic*.jpg"
' Neu muon tim ca o cac thu muc con thi inSub = TRUE, nguoc lai thi inSub = FALSE (mac dinh)
' Neu chi lay ten thi NameOnly = True (mac dinh). Neu muon lay toan bo duong dan thi NameOnly = FALSE.
' Neu tim tap tin thi folder = False (mac dinh). Neu tim thu muc thi folder = True.
' Ham bat dau tim trong thu muc khoi dong FolderStart
' Ket qua tim kiem duoc tra ve trong mang result co chi so tinh tu 1
Dim count As Long, f As Object, fso As Object, SubF As Object, files As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FolderExists(FolderStart) Then
If sFilter = "" Then sFilter = "*"
Set f = fso.GetFolder(FolderStart)
On Error Resume Next
count = f.files.count
If Err.Number Then
Err.Clear
On Error GoTo 0
Else
On Error GoTo 0
Set files = IIf(folder, f.SubFolders, f.files)
For Each SubF In files
If LCase(SubF.Name) Like LCase(sFilter) Then
If IsEmpty(result) Then
ReDim result(1 To 1)
count = 0
Else
count = UBound(result)
End If
ReDim Preserve result(1 To count + 1)
If NameOnly Then
result(UBound(result)) = SubF.Name
Else
result(UBound(result)) = SubF.Path
End If
End If
If inSub And folder Then
ListFilesOrFolders SubF.Path, result, sFilter, True, True, NameOnly
End If
Next SubF
If inSub And Not folder Then
For Each SubF In f.SubFolders
ListFilesOrFolders SubF.Path, result, sFilter, False, True, NameOnly
Next
End If
End If
Set f = Nothing
End If
Set fso = Nothing
End Sub
' Các ví dụ dùng
Sub test1()
Dim result, k As Long
' tất cả tập tin trong thư mục "c:\1" và các thư mục con, chỉ tên thôi
ListFilesOrFolders "c:\1", result, "", , True
If Not IsEmpty(result) Then
For k = 1 To UBound(result)
Debug.Print result(k)
Next k
End If
End Sub
Sub test2()
Dim result, k As Long
' tất cả tập tin trong thư mục "c:\1", chỉ tên thôi
ListFilesOrFolders "c:\1", result, ""
If Not IsEmpty(result) Then
For k = 1 To UBound(result)
Debug.Print result(k)
Next k
End If
End Sub
Sub test3()
Dim result, k As Long
' tất cả thư mục trong thư mục "c:\1", chỉ tên thôi
ListFilesOrFolders "c:\1", result, "", True
If Not IsEmpty(result) Then
For k = 1 To UBound(result)
Debug.Print result(k)
Next k
End If
End Sub
Sub test4()
Dim result, k As Long
' tất cả thư mục trong thư mục "c:\1" và các thư mục con, chỉ tên thôi
ListFilesOrFolders "c:\1", result, "", True, True
If Not IsEmpty(result) Then
For k = 1 To UBound(result)
Debug.Print result(k)
Next k
End If
End Sub