【发布时间】:2015-03-07 00:26:54
【问题描述】:
我正在尝试爬过某个驱动器并从隐藏在子目录中的某些 .xls 文件中获取数据。驱动器超过 TB,并且文件夹的层次结构并不相同,所以我正在浏览所有文件夹。到目前为止,脚本运行良好。
问题是,驱动器中有压缩文件。至少有一半的文件是压缩格式。我如何也可以爬取这些文件?
这是我的代码中爬过子目录的部分。还有另一个函数“TrailingSlash”,如果它还没有,它只是在字符串后面附加一个“\”。我在我的 cmets 中感谢作者。
Public Function recursiveDir(colFiles As Collection, strFolder As String, strFileSpec As String, bIncludeSubfolders As Boolean) as Collection
'From Ammara.com/access_image_faq/recursive_folder_search.html
'Recursive function to search document tree from specific file extension
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
Dim colFiles As New Collection
Dim counter As Integer
'Add files in strFolder matching strFileSpec to colFiles
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
On Error Resume Next
Do While strTemp <> vbNullString
colFiles.Add (strFolder & strTemp)
counter = counter + 1
Debug.Print ("files found: " & counter)
strTemp = Dir
Loop
If bIncludeSubfolders Then
'Fill colFolders with list of subdirectories of strFolder
strTemp = Dir(strFolder, vbDirectory)
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call recursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call recursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
recursiveDir = colFiles
End Function
该函数将所有路径字符串添加到集合“colFolders”中,然后我用它来打开和提取数据。我现在认为可能没有一种简单的方法可以将字符串路径返回到压缩文件夹中的文件。当此函数遇到 zip 时,可能需要调用一个单独的函数,该函数依次爬取压缩文件夹并将特定文件提取到本地目的地(只要我不必提取整个文件夹,我们应该很好)。
我有点迷失了我应该做什么。谷歌搜索指向我使用 shell.Application。我对shell一窍不通,这是我该走的路吗?
非常感谢 - 你们都很棒!
【问题讨论】:
-
This answer 可能会有所帮助,如果您可以遍历
objShell.NameSpace(strZipFilename).Items -
所以想法是遍历 objShell,类似于使用 Dir() 迭代?我想我必须深入研究 Application.Shell。这将如何与挖掘子目录一起工作?
-
当您浏览每个子目录时,当您找到一个 zip 文件时,您可以搜索项目 - zip 文件中的项目在解压缩之前没有目录结构。
-
哦!好决定!所以zip文件是完全平坦的?这使这变得容易得多。
-
等待.. 但是您提供的答案,该示例暗示文件层次结构为“folderlevel1/folderlevel2/folderlevel3/Myfile.csv”不?
标签: vba excel automation zip