Excel VBA嵌套循环在子文件夹中查找所有文件

时间:2018-11-26 19:43:28

标签: excel vba excel-vba

我正在尝试查找包含子文件夹的文件夹中的所有文件。到目前为止,我已经获得了找到目录中所有子文件夹的代码,以及找到了文件夹中所有文件的循环,但是我很难将它们放在一起。

查找文件夹中的所有文件:

Sub NamesInFolder()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
'Dim j As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("M:\path")

i = 1

'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'print file name
Cells(i + 1, 1) = objFile.Name
'print file path
Cells(i + 1, 2) = objFile.Path
' print creation date
Cells(i + 1, 3) = objFile.DateCreated

i = i + 1
Next objFile
End Sub

找到文件夹中的所有子文件夹:

Sub FilesInFolder()
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim i As Integer

'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object


Set objFolder = objFSO.GetFolder("M:\Path")


i = 1


'loops through each file in the directory and prints their names and path
For Each objSubFolder In objFolder.subfolders
    'print folder name
    Cells(i + 1, 1) = objSubFolder.Name
    'print folder path
    Cells(i + 1, 2) = objSubFolder.Path
    i = i + 1
Next objSubFolder

End Sub

A,这段代码无法正常工作,试图找到其中的所有子文件夹和文件

Sub Names_Files_InFolder()

Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim objSubFolder As Object
Dim i As Integer
Dim j As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("C:\Users\IJoyce\Desktop\PaperSub2")

i = 1

For Each objSubFolder In objFolder.subfolders
For Each objFile In subfolders.Files

Cells(i + 1, 1) = objFile.Name
'print file path
Cells(i + 1, 2) = objFile.Path
' print creation date
Cells(i + 1, 3) = objFile.DateCreated

Cells(i + 1, 4) = objSubFolder.Name

i = i + 1
Next objFile
Next objSubFolder


End Sub

0 个答案:

没有答案