I am trying to Delete a Folder from the Zip file.
So My file structure is like:
Inside First:
I tried to use the code here Deleting Files from A Zip By Siddharth Rout, But it only Moves the files, apparently the folder becomes empty, but isn't deleted from the Zip.
Code:
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
Apparently it moves all the files to the folder Dump, but the folder named Second
stays intact in the Zip. Though all the files from second are also moved.
I can use the command Kill
& RmDir
afterwards to delete the moved files and Folder. But how to make the Second Folder Vanish from Zip.
Note:
I was able to delete the folder.
CreateObject("Shell.Application").Namespace("C:\Users\mohit.bansal\Desktop\Test\test\first.zip\first\second").Self.Verbs.Item(4).DoIt
As GSerb pointed out it may be better to use InvokeVerb)"Delete"
to delete the folder.
CreateObject("Shell.Application").Namespace("C:\Users\mohit.bansal\Desktop\Test\test\first.zip\first\second").Self.InvokeVerb ("Delete")
I have not been able to suppress the file deletion conformation dialog.
So using .Self.Verbs.Item(4)
we can access the Right Click Options starting with 0.
Demo:
My final working solution was to copy the contents of the Xip file to a temp folder, delete the sub folder, delete the original zip file, create a new zip file, and copy the remaining items to the new zip file.
Usage:
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
Thanks for the Mikku and SiddharthRout for there help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With