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

问题描述 投票:2回答:3

我使用文件资源管理器映射了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版本的解决方案。有任何想法吗?

vba excel-vba excel-2010 dir excel
3个回答
2
投票

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

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

    If FileExists Then MsgBox "File found in M:"

2
投票

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

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

Y:\Projects\Proj1\File1.xlsx

到完整的映射路径,例如

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

解决了这个问题


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
© www.soinside.com 2019 - 2024. All rights reserved.