VBA目录功能无法在Excel 2010上运行

时间:2014-02-28 23:37:26

标签: vba excel-vba excel-2010 dir excel

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

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

 Dim FileExists as Boolean

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

 If FileExists Then MsgBox "File found in M:"

我在Excel 2007上运行该宏并且工作正常。当我在Excel 2010上运行它时,Dir("M:\myfile")总是返回“”,即使该文件存在于指定位置。我找不到适用于两个Excel版本的解决方案。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

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

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

    If FileExists Then MsgBox "File found in M:"

答案 1 :(得分:2)

我发现如果我使用完整的网络名称,它首先运行。这不仅仅是在VBA中,而且还有一些快捷方式 - 他们返回&#34;文件无法找到&#34;。

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

Y:\Projects\Proj1\File1.xlsx

到完整的映射路径,例如

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

解决了问题

答案 2 :(得分:1)

以下是如何使用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
相关问题