VBA 复制到 zip 文件 returns 错误

VBA copy to zip file returns error

我已经编写了一个脚本,使用改编自 www.rondebruin.nl 的代码将文件夹中的所有文件添加到 zip 文件,但我一直收到错误 'Object variable or With block variable not set'。

Function ZipDir(FolderName As String, ZipName As String) As String
'Copied from: http://www.rondebruin.nl/win/s7/win001.htm
Dim FileNameZip ', FolderName
Dim strDate As String, DefPath As String
Dim oApp As Object

'Create empty Zip File
NewZip ZipName

Set oApp = CreateObject("Shell.Application")
'Copy the files to the compressed folder
oApp.Namespace(ZipName).CopyHere oApp.Namespace(FolderName).items '<<ERROR HERE

'Keep script waiting until Compressing is done
On Error Resume Next
Do Until oApp.Namespace(ZipName).items.Count = _
    oApp.Namespace(FolderName).items.Count
    Application.Wait (Now + TimeValue("0:00:01"))
Loop
On Error GoTo 0

MsgBox "You find the zipfile here: " & ZipName
End Function

oApp.Namespace(ZipName).CopyHere oApp.Namespace(FolderName).items 行的代码错误。但是,如果我像这样显式声明源文件和目标文件:oApp.Namespace("C:\MyZip.Zip").CopyHere "C:\Temp\MyFile.pdf"

如果我从上面更改 zip 名称或文件名,则会出错。

有什么想法吗?

使用 Shell.Application 对象时,您应该将所有路径和文件名作为变体而不是字符串传递。

如果您查看 Ron 的代码,您会发现他就是这样做的。

正如他在那一页上所说:

Note: Do not Dim for example FileNameZip as String in the code examples. This must be a Variant, if you change this the code will not work.