'-------------------------------------------
'獲取某文件夾下所有文件和子目錄下的文件
'-------------------------------------------
Sub getAllFile()
Cells.ClearContents
Call getFileNm(ChooseFolder(), 0, 0)
MsgBox "處理完成!"
End Sub
'-------------------------------------------
'獲取目標文夾路徑
'-------------------------------------------
Public Function ChooseFolder() As String
Dim dlgOpen As FileDialog
Set dlgOpen = Application.FileDialog(msoFileDialogFolderPicker)
With dlgOpen
If .Show = -1 Then
ChooseFolder = .SelectedItems(1)
End If
End With
Set dlgOpen = Nothing
End Function
'-------------------------------------------
'獲取文件夾下所有文件和文件夾名稱
'row worksheet里的打印行
'col worksheet里的打印列(根據層次顯示)
'-------------------------------------------
Public Sub getFileNm(ByVal subFolderPath As String, _
ByRef row As Integer, _
ByVal col As Integer)
Dim fileName As String
Dim subFolderVisited As String
col = col + 1
subFolderPath = subFolderPath & "\"
fileName = Dir(subFolderPath, vbDirectory)
Do While fileName <> ""
If fileName <> "." And fileName <> ".." Then
If GetAttr(subFolderPath & fileName) And vbDirectory Then
'文件夾的場合
row = row + 1
Worksheets(1).Cells(row, col) = fileName
Call getFileNm(subFolderPath & fileName, row, col)
Else
'文件的場合
row = row + 1
Worksheets(1).Cells(row, col) = fileName
End If
End If
'獲取執行遞歸前的下一個文件
subFolderVisited = Dir(subFolderPath, vbDirectory)
Do While subFolderVisited <> fileName
subFolderVisited = Dir
Loop
fileName = Dir
Loop
End Sub