如果在Shell.Application Copyhere中使用string或变体,则无法写入zip文件

我有与NameSpace的CopyHere函数的麻烦。 我正在尝试创build一个包含一堆日志的zip文件。 我可以创build压缩文件,但使用NameSpace.CopyHere时,如果使用string或包含string的变体,它不会将文件写入zip压缩文件。

例如,我有一个位于P:\ test2.txt的文件。

如果我使用这些行:

objApp.Namespace(sZipArchive).CopyHere sFile objApp.Namespace(sZipArchive).CopyHere vLogs(i) 

其中sFile = vLogs(i)=“P:\ test2.txt

test2.txt文件将不会被复制到zip压缩文件中。

但是,如果我使用这一行:

 objApp.Namespace(sZipArchive).CopyHere "P:\test2.txt" 

然后,该文件被复制到zip文件中。

如果我检查sFile或vLog(i)是否为“P:\ test2.txt”,我可以看到它们是一样的。

有什么我在这里错过了为什么前两行不工作,但第三个呢?

感谢您的时间。

全部子:

 Private Sub BtnSaveToZip_Click() Dim bEndRow, bTest As Boolean Dim iRow, iCount As Integer Dim sZipArchive, sDate, sFolderExists, sFile As String Dim vLogs, vFilename As Variant Dim objApp As Object sDate = Date sDate = Replace(sDate, "/", "") ' set date format to DDMMYYYY instead of DD/MM/YYYY sZipArchive = LblLogArchive + "\" + sDate sFolderExists = Dir(sZipArchive) If sFolderExists = "" Then CreateDir (sZipArchive) ' if the subfolder with the date does not exists, create it End If sZipArchive = sZipArchive + "\" + wsContacts.Range("B7").Value + " Logs_" + sDate + ".zip" 'Check if file is open If FileLocked(sZipArchive) Then MsgBox sZipArchive + " already open. Please close the archive." Exit Sub End If 'Creating the zip file from Ron de Bruin NewZip (sZipArchive) 'filling the zip file Set objApp = CreateObject("Shell.Application") bEndRow = False iRow = gFirstData Do While bEndRow = False If Not IsEmpty(wsLogs.Cells(iRow, gTestCase).Value) Then If Not IsEmpty(wsLogs.Cells(iRow, gLog).Value) Then vLogs = Split(wsLogs.Cells(iRow, gLog).Value, ";") For i = 0 To UBound(vLogs) - 1 sFile = vLogs(i) ' Debug only If sFile = "P:\test2.txt" Then 'Debug only objApp.Namespace(sZipArchive).CopyHere vLogs(i) ' if I put "P:\test2.txt", it works correctly 'Keep script waiting 5s for debug purpose Application.Wait (Now + TimeValue("00:00:05")) End If Next End If iRow = iRow + 1 Else bEndRow = True End If Loop MsgBox "Zip successfully created" Set objApp = Nothing End Sub 

如果这个工作

 objApp.Namespace(sZipArchive).CopyHere "P:\test2.txt" 

sFilevLogs(i)似乎是P:\test2.txt相同,那么我相信它可能是一个前导或尾随空间问题。 尝试这个

 objApp.Namespace(sZipArchive).CopyHere Trim(sFile) 

要么

 objApp.Namespace(sZipArchive).CopyHere Trim(vLogs(i)) 

另一种检查sFilevLogs(i)包含有效path的方法是使用DIR

另一种debugging方法是逐步执行代码,然后在“立即”窗口中input该代码

 ?=vLogs(i)="P:\test2.txt" ?=sFile="P:\test2.txt" 

在两种情况下你都应该得到一个真实的。 如果你不这样做,那么你的问题:)