使用VBA创建zip文件错误



在使用VBA创建压缩文件时遇到一些问题。当我运行文件时,我得到以下错误:

Object variable or With block variable not set.

当执行到这一行时触发:

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

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

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:userssomeuserdesktoptest", "C:userssomeuserdesktoptest.zip")

致任何有此问题的人。事实证明,这与空文件夹有关。如果下面的文件夹为空,则触发异常。

ShellApp.Namespace(folderToZipPath).items

最新更新