VBA Dir函数在Excel 2010上无法工作

3

我使用文件资源管理器映射了一个内部网络位置,即将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版本上都工作的解决方案。有什么想法吗?


看看FileSystemObject吧。比愚蠢的dir函数更直观。 - Brad
2
应该是 Dir("M:\myfile\") 而不是 Dir("M:\myfile") - Qbik
@Qbik的评论对于文件来说并不相关,但是对于使用Dir()函数列出目录中的文件非常重要——在Windows上,即使在Mac上尾部斜杠是可选的,你仍然需要包含尾部反斜杠(Application.PathSeparator)。 - Jamie Ciocco
3个回答

2

你可以在文件路径的结尾处添加文件扩展名作为通配符。我在Excel 2010中试过,它对我有效。

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

    If FileExists Then MsgBox "File found in M:"

谢谢Santosh。实际上,我正在尝试查找的文件名是完整的名称和扩展名,而不是“myfile”。它在映射单元M上无法工作 = http://intranet.XXXX.com/mydir/。 - user3366899
忘了说,原始宏适用于任何其他驱动器,例如C:\或甚至映射的网络单元。 - user3366899
您要访问的驱动器,是 Citrix 环境吗? - Santosh

2
我发现如果我使用完整的网络名称,它会第一次就工作。这不仅仅是在VBA中,也存在于一些快捷方式中 - 它们返回“找不到文件”的错误信息。
将映射的快捷方式更改为,例如:
Y:\Projects\Proj1\File1.xlsx

将其完整映射到路径,例如:

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

问题已被解决。


这将无法与IP \10.254.0.10\SomeDir类型的映射服务器一起使用,也无法在Internet名称\server-name.com\SomeDir上使用。 - Siyon DP

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

我是Excel VBA的新手。我将您的代码复制粘贴到VBA中,只更改了路径。然后我创建了一个宏来调用该函数。在第一行“Option Compare Database”上出现错误(“预期文本或二进制文件”)。看起来您的代码不适用于Excel VBA,是吗? - user3366899

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接