FileExists 方法

如果指定的文件存在,则返回 True;如果不存在,则返回 False。

语法

object.FileExists(filespec)

参数:

  • Object必需。始终为 FileSystemObject 的名称。
  • Filespec必需。有待确定是否存在的文件的绝对路径。

以下示例说明了 FileExists 方法的用法。

示例 1

Function CheckFileExists(filespec)
    Dim fso, msg
    Set fso = CreateObject("Scripting.FileSystemObject")
    If (fso.FileExists(filespec)) Then
        msg = filespec & " exists."
    Else
        msg = filespec & " doesn't exist."
    End If
    CheckFileExists = msg
End Function

' Sample usage
Dim result
result = CheckFileExists("C:\example.txt")
' Outputs: C:\example.txt exists. or C:\example.txt doesn't exist.

示例 2

Function CheckMultipleFiles(files)
    Dim fso, file, result
    Set fso = CreateObject("Scripting.FileSystemObject")
    For Each file In files
        If fso.FileExists(file) Then
            result = result & file & " exists."
        Else
            result = result & file & " doesn't exist."
        End If
    Next
    CheckMultipleFiles = result
End Function

' Sample usage
Dim filesToCheck, checkResult
filesToCheck = Array("C:\file1.txt", "C:\file2.txt", "D:\file3.txt")
checkResult = CheckMultipleFiles(filesToCheck)
' Outputs the existence status of each file in the array.