分享

vba判断文件是否存在的两种方法

 昵称QAb6ICvc 2017-06-08

方法1. 用VBA自带的dir()判断,代码如下:

在 Microsoft Windows 中, Dir 支持多字符 (*)和单字符 (?) 的通配符来指定多重文件

Function IsFileExists(ByVal strFileName As String) As Boolean  
    If Dir(strFileName, 16) <> Empty Then  
        IsFileExists = True  
    Else  
        IsFileExists = False  
    End If  
End Function  
  
Sub Run()  
    If IsFileExists("D:\vba\abc.txt") = True Then  
    ' 文件存在时的处理  
        MsgBox "文件存在!"  
    Else  
    ' 文件不存在时的处理  
        MsgBox "文件不存在!"  
    End If  
End Sub 


方法2. 用Windows的文件系统函数进行判断,代码如下:

Function IsFileExists(ByVal strFileName As String) As Boolean  
    Dim objFileSystem As Object  
  
    Set objFileSystem = CreateObject("Scripting.FileSystemObject")  
    If objFileSystem.fileExists(strFileName) = True Then  
        IsFileExists = True  
    Else  
        IsFileExists = False  
    End If  
End Function  
  
Sub Run()  
    If IsFileExists("D:\vba\abc.txt") = True Then  
    ' 文件存在时的处理  
        MsgBox "文件存在!"  
    Else  
    ' 文件不存在时的处理  
        MsgBox "文件不存在!"  
    End If  
End Sub 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多