VBA Dir 函数不适用于 Excel 2010

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22107858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:09:53  来源:igfitidea点击:

VBA Dir function not working on Excel 2010

vbaexcel-vbaexcel-2010direxcel

提问by user3366899

I mapped an intranet location using the File Explorer. i.e. mapped http://intranet.XXXXXXX.com/mydir/to M:\

我使用文件资源管理器映射了一个 Intranet 位置。即映射http://intranet.XXXXXXX.com/mydir/到 M:\

I'm using the Dirfunction to test if a file is present in that location:

我正在使用该Dir函数来测试该位置是否存在文件:

 Dim FileExists as Boolean

 FileExists = Dir("M:\myfile") <> ""

 If FileExists Then MsgBox "File found in M:"

I run that macro on Excel 2007 and it Works Fine. When I run it on Excel 2010 though, Dir("M:\myfile")always returns "", even if the file is present in the specified location. I can′t find a solution that will work on both Excel versions. Any ideas?

我在 Excel 2007 上运行该宏,它运行良好。但是,当我在 Excel 2010 上运行它时Dir("M:\myfile"),即使文件存在于指定位置,也始终返回“”。我找不到适用于两个 Excel 版本的解决方案。有任何想法吗?

回答by Santosh

You may add file extension as a wildcard character at the end of filepath. I gave a try in excel 2010 and it worked for me.

您可以在文件路径末尾添加文件扩展名作为通配符。我尝试了 excel 2010,它对我有用。

  Dim FileExists As Boolean
    FileExists = Dir("D:\myfile" & "*.txt") <> ""

    If FileExists Then MsgBox "File found in M:"

回答by Scott

I found that if I use the full network name, it works first go. This wasn't just in VBA, but also some shortcuts also - they returned "File could not be found".

我发现如果我使用完整的网络名称,它首先起作用。这不仅仅是在 VBA 中,还有一些快捷方式 - 他们返回“找不到文件”。

Changing from the mapped shortcut, e.g.

从映射的快捷方式更改,例如

Y:\Projects\Proj1\File1.xlsx

to the full mapped path, e.g.

到完整的映射路径,例如

\server\Department\Projects\Proj1\File1.xlsx

Fixed the problem

修复了问题

回答by Wayne G. Dunn

Here is how to use FSO to do what you want:

以下是如何使用 FSO 来执行您想要的操作:

Option Explicit

Function test_it()
    'Test the Function - must pass the file path and name
    Debug.Print Does_File_Exist("C:\temp\form1.txt")
End Function

Private Function Does_File_Exist(sFullPath) As Boolean
' Will return True or False if file exists.
' Provide the fully qualified path and file name.
' You can disable the MsgBox displays after testing

Dim oFs         As New FileSystemObject
Dim oFile       As File

    Set oFs = New FileSystemObject
    If oFs.FileExists(sFullPath) Then
        Does_File_Exist = True
        MsgBox "Found file: " & sFullPath
    Else
        Does_File_Exist = False
        MsgBox "File not found: " & sFullPath
    End If

    Set oFs = Nothing
End Function