我正在尝试从Zip文件中删除文件夹。
所以我的文件结构是这样的:
内部优先:
我尝试在此处使用代码从 Siddharth Rout的“从Zip删除文件”,但是它仅移动文件,显然文件夹变为空,但未从Zip删除。
码:
Sub del()
Dim oApp As Object
Dim fl As Object
Set oApp = CreateObject("Shell.Application")
For Each fl In oApp.Namespace("C:\Users\mohit.bansal\Desktop\Test\test\first.zip\first").Items
'Path to a folder inside the Zip
oApp.Namespace("C:\Users\mohit.bansal\Desktop\Test\test\Dump").MoveHere (fl.path)
Next
End Sub
Run Code Online (Sandbox Code Playgroud)
显然,它将所有文件移动到文件夹Dump,但名为SecondZip 的文件夹保持不变。尽管秒的所有文件也被移动了。
之后,我可以使用命令Kill&RmDir删除已移动的文件和文件夹。但是,如何使第二个文件夹从Zip中消失。
注意:
我能够删除该文件夹。
Run Code Online (Sandbox Code Playgroud)CreateObject("Shell.Application").Namespace("C:\Users\mohit.bansal\Desktop\Test\test\first.zip\first\second").Self.Verbs.Item(4).DoIt
正如GSerb所指出的,最好使用InvokeVerb)"Delete"删除文件夹。
Run Code Online (Sandbox Code Playgroud)CreateObject("Shell.Application").Namespace("C:\Users\mohit.bansal\Desktop\Test\test\first.zip\first\second").Self.InvokeVerb ("Delete")
因此,使用,.Self.Verbs.Item(4)我们可以访问从0开始的右键单击选项。
演示:
我最后的工作解决方案是将Xip文件的内容复制到temp文件夹,删除子文件夹,删除原始zip文件,创建新的zip文件,然后将其余项目复制到新的zip文件。
用法:
Run Code Online (Sandbox Code Playgroud)DeleteZipSubDirectory "E:\first.zip","\first\second"
Sub DeleteZipSubDirectory(ZipFile As Variant, SubFolderRelativePath As Variant)
Dim tempPath As Variant
'Make Temporary Folder
tempPath = Environ("Temp") & "\"
Do While Len(Dir(tempPath, vbDirectory)) > 0
tempPath = tempPath & "0"
Loop
MkDir tempPath
Dim control As Object
Set control = CreateObject("Shell.Application")
'Copy Zip Contents to Temporary Folder
control.Namespace(tempPath).CopyHere control.Namespace(ZipFile).Items
'Debug.Print tempPath
With CreateObject("Scripting.FileSystemObject")
'Delete Target Folder
.DeleteFolder tempPath & SubFolderRelativePath
'Delete Original FIle
Kill ZipFile
'First we create an empty zip file: https://www.exceltrainingvideos.com/zip-files-using-vba/
Open ZipFile For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
'Copy the Remaining Items into the new Zip File
control.Namespace(ZipFile).CopyHere control.Namespace(tempPath).Items
Application.Wait Now + TimeValue("0:00:02")
'Delete Temporary Folder
.DeleteFolder tempPath
End With
End Sub
Run Code Online (Sandbox Code Playgroud)
感谢Mikku和SiddharthRout的帮助。
| 归档时间: |
|
| 查看次数: |
275 次 |
| 最近记录: |