首页 > 解决方案 > 使用 VBA 创建 zip 文件错误

问题描述

在使用 VBA 创建文件的 zip 时遇到一些问题。当我运行文件时,出现以下错误:

Object variable or With block variable not set.

当执行到达这一行时触发:

ShellApp.Namespace(zippedFileFullName).CopyHere ShellApp.Namespace(folderToZipPath).items.

我对 VBA 不是很熟悉,但文件Option Strict On顶部建议的 MS 文档。但是,当我添加它时,我又遇到了另一个错误:

Expected: Base or Compare pr Explicit or Private.

知道这里发生了什么吗?

Sub CreateZipFile(folderToZipPath As Variant, zippedFileFullName As Variant)

    Dim ShellApp As Object

    'Create an empty zip file
    Open zippedFileFullName For Output As #1
    Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1

    'Copy the files & folders into the zip file
    Set ShellApp = CreateObject("Shell.Application")
    ShellApp.Namespace(zippedFileFullName).CopyHere ShellApp.Namespace(folderToZipPath).items

    'Zipping the files may take a while, create loop to pause the macro until zipping has finished.
    On Error Resume Next
    Do Until ShellApp.Namespace(zippedFileFullName).items.Count = ShellApp.Namespace(folderToZipPath).items.Count
        Application.Wait (Now + TimeValue("0:00:01"))
    Loop
    On Error GoTo 0

End Sub
Call CreateZipFile("C:\users\someuser\desktop\test", "C:\users\someuser\desktop\test.zip")

标签: vba

解决方案


对于其他有此问题的人。原来与空文件夹有关。如果下面的文件夹为空,则触发了异常。

ShellApp.Namespace(folderToZipPath).items

推荐阅读