FileSystemObject FileExists在一台计算机上运行,​​但不在另一台计算机上运行

时间:2014-07-29 23:29:39

标签: excel vba excel-vba excel-2010 fso

在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提取压缩文件时,压缩文件对象的Name属性不包含扩展名如果Windows资源管理器隐藏扩展名且文件具有已注册的扩展名。例如:

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)

1 个答案:

答案 0 :(得分:0)

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