VB 代码示例:判断文件是否存在
以下是使用 VB 代码依次判断文件 'a.txt' 和 'b.txt' 是否存在的示例:
Sub CheckFilesExistence()
Dim filePaths As Variant
filePaths = Array('C:\path\to\a.txt', 'C:\path\to\b.txt') ' 定义文件路径数组
Dim i As Integer
For i = LBound(filePaths) To UBound(filePaths) ' 遍历文件路径数组
If FileExists(filePaths(i)) Then ' 调用 FileExists 函数判断文件是否存在
MsgBox filePaths(i) & ' exists.' ' 文件存在时显示消息框
Else
MsgBox filePaths(i) & ' does not exist.' ' 文件不存在时显示消息框
End If
Next i
End Sub
Function FileExists(filePath As String) As Boolean
FileExists = Len(Dir(filePath)) > 0 ' 使用 Dir 函数判断文件是否存在
End Function
在上面的示例中,我们首先定义了一个名为 CheckFilesExistence 的子过程,其中声明了一个变量 filePaths,并将包含文件 'a.txt' 和 'b.txt' 的路径存储在该变量中。然后,使用 For 循环遍历 filePaths 数组,对每个文件路径调用 FileExists 函数来判断文件是否存在。最后,根据文件是否存在,显示相应的消息框。
FileExists 函数使用 Dir 函数来检查文件是否存在。如果 Dir(filePath) 返回的字符串长度大于 0,则表示文件存在,否则表示文件不存在。
原文地址: https://www.cveoy.top/t/topic/f2o7 著作权归作者所有。请勿转载和采集!