从Zip文件中删除文件夹

Mik*_*kku 7 excel zip vba

我正在尝试从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 的文件夹保持不变。尽管秒的所有文件也被移动了。

之后,我可以使用命令KillRmDir删除已移动的文件和文件夹。但是,如何使第二个文件夹从Zip中消失。

注意:

  • 我并不是要从Zip中移走所有文件,这只是保持代码简短的测试条件。
  • 我不是在寻找一种解决方法来解压缩文件,删除文件夹并重新压缩所有内容。
  • 让我知道是否需要其他信息。

Tin*_*Man 8

我能够删除该文件夹。

CreateObject("Shell.Application").Namespace("C:\Users\mohit.bansal\Desktop\Test\test\first.zip\first\second").Self.Verbs.Item(4).DoIt
Run Code Online (Sandbox Code Playgroud)

正如GSerb所指出的,最好使用InvokeVerb)"Delete"删除文件夹。

 CreateObject("Shell.Application").Namespace("C:\Users\mohit.bansal\Desktop\Test\test\first.zip\first\second").Self.InvokeVerb ("Delete")
Run Code Online (Sandbox Code Playgroud)

我无法取消文件删除确认对话框。 在此处输入图片说明


因此,使用,.Self.Verbs.Item(4)我们可以访问从0开始的右键单击选项。

演示:

在此处输入图片说明

附录

我最后的工作解决方案是将Xip文件的内容复制到temp文件夹,删除子文件夹,删除原始zip文件,创建新的zip文件,然后将其余项目复制到新的zip文件。

用法:

  DeleteZipSubDirectory "E:\first.zip","\first\second"   
Run Code Online (Sandbox Code Playgroud)
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的帮助。