vba判斷文件是否存在的兩種方法(轉)


方法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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM