判断指定目录下的指定文件是否存在
以判断D盘根目录下是否存在"Excel VBA其实很简单.xlsm"为例,想知道这个文件是否存在,最简单的办法就是用Dir函数尝试获取该文件名,再通过其返回结果判断文件是否存在。代码可以写为:
Sub 判断文件是否存在()
Dim myFileName As String
'指定带完整目录的文件夹名称
myFileName = "D:\Excel VBA其实很简单.xlsm"
If Len(Dir(myFileName, vbDirectory)) > 0 Then
MsgBox "该文件存在"
Else
MsgBox "该文件不存在"
End If
End Sub
当然,对于同一个问题,解决的思路不同,代码也不一定相同。比如,要判断文件是否存在,还可以用下面的代码:
Sub 判断文件是否存在()
Dim myFile As String
Dim fso As Scripting.FileSystemObject
myFile = "D:\Excel VBA其实很简单.xlsm" '指定带完整路径的文件名
Set fso = New Scripting.FileSystemObject
If fso.FileExists(myFile) = True Then
MsgBox "文件 " & myFile & " 存在"
Else
MsgBox "文件 " & myFile & " 不存在"
End If
Set fso = Nothing
End Sub
页:
[1]