VB 代码判断文件是否存在:示例教程

本教程将向您展示如何使用 VB 代码依次判断多个文件是否存在。

代码示例

Sub CheckFilesExistence()
    Dim filePaths As Variant
    filePaths = Array('d:\a.txt', 'd:\b.txt') ' 定义文件路径数组
    
    Dim fileExists As Boolean
    For Each filePath In filePaths
        fileExists = FileExists(filePath)
        If fileExists Then
            MsgBox filePath & ' 存在'
        Else
            MsgBox filePath & ' 不存在'
        End If
    Next filePath
End Sub

Function FileExists(filePath As String) As Boolean
    Dim fileSystem As Object
    Set fileSystem = CreateObject('Scripting.FileSystemObject')
    FileExists = fileSystem.FileExists(filePath)
End Function

请确保将文件路径替换为实际要检查的文件路径。

代码解释

  1. 定义文件路径数组: 使用 Array() 函数创建包含文件路径的数组。
  2. 循环遍历数组: 使用 For Each 循环遍历每个文件路径。
  3. 使用 FileExists 函数判断文件是否存在: 使用 FileExists 函数检查每个文件路径所指向的文件是否存在。
  4. 显示结果: 使用 MsgBox 函数显示每个文件是否存在的结果。

FileExists 函数

FileExists 函数使用 FileSystemObject 对象来检查文件是否存在。该函数接受一个字符串参数,表示要检查的文件路径。如果文件存在,函数返回 True;否则返回 False

通过学习本教程,您已经掌握了使用 VB 代码判断文件是否存在的方法。

VB 代码判断文件是否存在:示例教程

原文地址: http://www.cveoy.top/t/topic/f1ZP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录