在VB6中,你可以使用FileSystemObject
对象和Directory
对象来查找多级目录中的文件,并将文件路径存储在一个数组中。以下是一个函数示例,它会递归搜索指定目录及其所有子目录中的所有文件,并返回包含文件路径的字符串数组。
' 导入FileSystemObject库
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
' 递归搜索指定目录下的所有文件,并返回文件路径数组
Function GetFilesInDirectory(startPath As String) As String()
Dim fileList() As String
Dim fileCount As Integer
fileCount = 0
' 递归搜索文件
RecurseFiles FSO.GetFolder(startPath), fileList, fileCount
' 返回文件路径数组
ReDim Preserve fileList(fileCount - 1)
GetFilesInDirectory = fileList
End Function
' 递归搜索文件的辅助函数
Sub RecurseFiles(folder As Object, ByRef fileList() As String, ByRef fileCount As Integer)
Dim subfolder As Object
Dim file As Object
For Each file In folder.Files
ReDim Preserve fileList(fileCount)
fileList(fileCount) = file.Path
fileCount = fileCount + 1
Next
For Each subfolder In folder.SubFolders
RecurseFiles subfolder, fileList, fileCount
Next
End Sub
使用这个函数,你可以通过指定开始目录来获取该目录及其所有子目录中的所有文件路径。例如:
Dim files() As String
Dim file As Variant
' 设置要搜索的起始目录
files = GetFilesInDirectory("C:\MyDirectory")
' 遍历并输出文件路径
For Each file In files
Debug.Print file
Next file
这段代码会打印出C:\MyDirectory
目录及其所有子目录中的每个文件的完整路径。