ExcelVBA判断文件或文件夹是否存在
【知识点】
Dir函数
返回一个 String,用以表示一个文件名、目录名或文件夹名称,它必须与指定的模式或文件属性、或磁盘卷标相匹配。
语法:dir(pathname)
代码
Sub dir_test_Folder()
Dim dirPath$
dirPath = ThisWorkbook.Path & "\新test\"
MsgBox FileFolderExists(dirPath)
End Sub
'自定义函数:可以判断文件或文件夹是否存在
Function FileFolderExists(strFullPath AsString) As Boolean
If Not Dir(strFullPath, 16) = vbNullString Then
FileFolderExists = True
Else
FileFolderExists = False
End If
End Function
由于:vbDirectory 指定无属性文件及其路径和文件夹。所以这也可以判断文件是否存在
【知识点2】FileSystemObject 对象- FolderExists方法
语法
oFileSysObj.FolderExists(folderspec)
【实例1】用FileSystemObject 对象- FolderExists方法判断文件夹是否存在
代码
Sub test_FolderExists()
Dim obj As Object
Set obj = CreateObject("scripting.FileSystemObject")
MsgBox obj.FolderExists(ThisWorkbook.Path & "\test\")
End Sub
应用:判断文件夹是否存在,如果不存在则创建
效果图
点击“确定”后创建新的文件夹,这里也可以添加语句
小结
判断文件或文件夹是否存在可以有两各方法
一、dir函数
二、FileSystemObject 对象- FolderExists方法