我已經寫了一個腳本來使用從www.rondebruin.nl改編的代碼將文件夾中的所有文件添加到zip文件,但我不斷收到錯誤'Object variable or With block variable沒有設置'。VBA複製到zip文件返回錯誤
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名稱或上面的文件名,那麼它會出錯。
任何想法?
您是否從ZipName和FolderName獲取有效路徑? – justkrys
是的。我甚至嘗試過使用直接窗口 - '?zipname'和'?Foldername',然後將這些值粘貼回代碼中。當我粘貼實際值時,但是當我使用ZipName或FolderName時,它不起作用... – GerHick
那麼它從哪裏得到ZipName和FolderName?它們是從調用此函數的方法還是用於此函數本身的直接窗口?如果你爲每一個做一個Debug.Print,它是否給你所期望的? – justkrys