📅  最后修改于: 2023-12-03 15:28:20.491000             🧑  作者: Mango
在VBA中,您可以使用递归方法来访问文件夹和其子文件夹中的所有文件和目录。以下是如何实现这一点的步骤:
Option Explicit
Dim fso As Object
Sub IterateFolders()
Dim folderPath As String
Dim objFolder As Object
Dim objFile As Object
Set fso = CreateObject("Scripting.FileSystemObject")
folderPath = InputBox("请输入文件夹路径:")
Set objFolder = fso.GetFolder(folderPath)
'遍历并处理该文件夹中的文件和文件夹
For Each objFile In objFolder.Files
'处理该文件
Next objFile
'递归遍历该文件夹中的所有子文件夹
For Each objSubfolder In objFolder.Subfolders
IterateSubfolders objSubfolder.Path
Next objSubfolder
Option Explicit
Dim fso As Object
Sub IterateFolders()
Dim folderPath As String
Dim objFolder As Object
Dim objFile As Object
Set fso = CreateObject("Scripting.FileSystemObject")
folderPath = InputBox("请输入文件夹路径:")
Set objFolder = fso.GetFolder(folderPath)
'遍历该文件夹中的文件和文件夹
For Each objFile In objFolder.Files
'TODO:在这里处理该文件
Next objFile
'递归遍历该文件夹中的所有子文件夹
For Each objSubfolder In objFolder.Subfolders
IterateSubfolders objSubfolder.Path
Next objSubfolder
End Sub
Private Sub IterateSubfolders(folderPath As String)
Dim objFolder As Object
Dim objFile As Object
Set objFolder = fso.GetFolder(folderPath)
'遍历该文件夹中的文件和文件夹
For Each objFile In objFolder.Files
'TODO:在这里处理该文件
Next objFile
'递归遍历该文件夹中的所有子文件夹
For Each objSubfolder In objFolder.Subfolders
IterateSubfolders objSubfolder.Path
Next objSubfolder
End Sub
现在,您已经了解了如何使用VBA迭代一个文件夹中的所有文件,能够对 VBA 程序员进行详细的介绍。