0

在 Excel 2010 VBA 中,我使用 FileSystemObject 的 FileExists 属性来检查文件是否存在。在我的电脑上它工作正常。但在另一台 Excel 2010 计算机上,它报告该文件不存在,而实际上我们在 Windows 资源管理器中看到该文件存在。在这两种情况下,被检查的文件都在本地硬盘上。

我在使用 Shell 解压缩文件后立即检查文件。我在解压缩后使用 DoEvents。该文件被提取到 zip 文件所在的同一文件夹中。

这是代码:

Dim oShell As Object, oZippedFile As Object, oUnzipTargetFolder As Object
Dim FSO As Object, oFile As Object, oFolder As Object
Dim strZipfileFullpath As Variant, strTargetFolderpath As Variant, strTargetFullpath As Variant 'NOT AS STRINGS!! (Shell error if strings)
Dim bFileCheckFsoFileExist As Boolean

Set oShell = CreateObject("shell.application")
Set FSO = CreateObject("scripting.filesystemobject")

strZipfileFullpath = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", MultiSelect:=False)

Set oFile = FSO.GetFile(strZipfileFullpath)
Set oFolder = oFile.ParentFolder
strTargetFolderpath = oFolder.Path & Application.PathSeparator
strTargetFullpath = strTargetFolderpath & oShell.Namespace(strZipfileFullpath).Items.Item(0).Name

oShell.Namespace(strTargetFolderpath).CopyHere oShell.Namespace(strZipfileFullpath).Items.Item(0) 'this zip has only one file.
DoEvents

bFileCheckFsoFileExist = FSO.FileExists(strTargetFullpath)

任何想法为什么这在一台计算机上运行良好,但在另一台计算机上报告该文件不存在,即使我们清楚地看到它是?

更新:

我想我会添加这个注释,以防它可能对遇到同样问题的其他人有所帮助。

基本的潜在问题是,当使用 Shell 提取压缩文件时,如果 Windows 资源管理器隐藏扩展名并且文件具有注册扩展名,则压缩文件对象的 Name 属性不包括扩展名。例如:

Dim strGofnZipfileFullpath As Variant
Dim oShell As Object, oShellZipfile As Object, oShellZippedFileInZipfile As Object
Dim strShellZippedFileInZipfileFilename As Variant 'NOT AS STRINGS!! (Shell error if strings)

strGofnZipfileFullpath = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", MultiSelect:=False)

Set oShell = CreateObject("shell.application")
Set oShellZipfile = oShell.Namespace(strGofnZipfileFullpath)
Set oShellZippedFileInZipfile = oShellZipfile.Items.Item(0) 'assumes only 1 file in zip. 
        strShellZippedFileInZipfileFilename = oShellZippedFileInZipfile.Name

如果 Windows 资源管理器设置为隐藏扩展名并且压缩文件具有已注册的扩展名,则 strShellZippedFileInZipfileFilename 不包括该扩展名。

但是,压缩文件对象 (oShellZippedFileInZipfile) 也有一个包含扩展名的 Path 属性。因此,您可以获得包含扩展名的文件名,如下所示:

strShellZippedFileInZipfileFilename = Right(oShellZippedFileInZipfile.Path, InStr(StrReverse(oShellZippedFileInZipfile.Path), Application.PathSeparator) - 1)
4

1 回答 1

0

要记住的一件事是 Windows 资源管理器中的文件夹选项。在这种情况下,这可能对您没有帮助,但是我遇到了许多 fso 交互,这些交互对于文件在 Windows 资源管理器中的显示方式存在很大问题。像您的系统显示文件扩展名这样简单的事情,而另一个不是,有时可能是查找文件的罪魁祸首。

于 2014-07-30T16:39:24.980 回答