如何获取压缩(ZIP)文件夹内的文件列表?VBA报错求助
压缩文件夹内提取文件信息的VBA解决方案
原问题:平时靠Ctrl+A全选后右键「复制为路径」获取文件名,但这个操作在压缩文件夹里没法用。运行原VBA代码时出现「运行时错误'76':路径未找到」——核心原因是FileSystemObject(FSO)无法直接识别压缩包内的虚拟路径,压缩包本身是单个文件,不是真实的磁盘文件夹结构。
要实现从压缩包里提取指定类型文件的信息,改用Shell.Application对象来访问压缩包内容,以下是修改后的代码:
Sub ExtractZipFileInfo() Dim zipPath As String Dim shellApp As Object Dim zipFolder As Object Dim fileItem As Object Dim i As Integer ' 获取A2单元格中的压缩包完整路径 zipPath = Range("A2").Value ' 检查路径有效性 If zipPath = "" Or Dir(zipPath) = "" Then MsgBox "请输入有效的压缩包路径!", vbExclamation Exit Sub End If ' 创建Shell.Application对象访问压缩包 Set shellApp = CreateObject("Shell.Application") Set zipFolder = shellApp.Namespace(zipPath) i = 4 ' 从第4行开始写入数据 ' 遍历压缩包内所有文件 For Each fileItem In zipFolder.Items ' 筛选PDF和TXT文件 If fileItem.Type = "Adobe Acrobat Document" Or fileItem.Type = "Text Document" Then Cells(i, 1) = zipPath ' 压缩包路径作为父路径 Cells(i, 2) = fileItem.Name ' 文件名 Cells(i, 3) = fileItem.Type ' 文件类型 Cells(i, 4) = fileItem.DateCreated ' 创建日期 Cells(i, 5) = fileItem.DateLastModified ' 修改日期 i = i + 1 End If Next fileItem ' 释放对象 Set fileItem = Nothing Set zipFolder = Nothing Set shellApp = Nothing MsgBox "文件信息提取完成!", vbInformation End Sub
注意事项
- 原生支持ZIP格式压缩包,若处理RAR等其他格式,需确保系统已安装对应压缩软件并关联了文件类型
- A2单元格必须输入压缩包的完整绝对路径,比如
C:\Documents\myfiles.zip - 带密码保护的压缩包无法直接用此代码访问,需先手动解压或添加密码验证逻辑
内容的提问来源于stack exchange,提问作者Tom Mullin
相关产品推荐
相关产品推荐

