![](/img/trans.png)
[英]excel vba code to check for a folder if it exists, if not create a folder
[英]VBA “Check if folder exists” works only when there is a file in the folder
我从www.rondebruin.nl获得了原始代码
它旨在测试目录中是否已存在文件夹。 我对其进行了修改以满足自己的需求,并且看起来效果很好。
今天,我发现只有在要测试的文件夹不是空的情况下,它才能正常工作。 如果为空,则返回false(即文件夹不存在)。
我不知道为什么会这样。
FolderPath = sPfad
If Right(FolderPath, 1) <> "\" Then
FolderPath = FolderPath & "\"
End If
TestStr = ""
On Error Resume Next
TestStr = Dir(FolderPath)
On Error GoTo 0
If TestStr = "" Then
Test_Folder_Exist_With_Dir = False
Exit Function
Else
Test_Folder_Exist_With_Dir = True
Exit Function
End If
我怀疑答案就在TestStr = Dir(FolderPath)
但无法TestStr = Dir(FolderPath)
探讨。 MSDN 文章基本上解释了Dir()
总是返回某些内容。 但是,给出的示例全部都是存在要返回的文件。
我基本上需要获取它,以便它识别文件夹,而不管其中是否有东西。
任何帮助表示赞赏!
如果文件夹存在,则以下行将返回大于0的数字,无论该文件夹中是否包含任何文件
len(dir("C:\Users\user\Desktop\Tests\tt", vbDirectory))
您可以尝试以下方法:
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(FolderPath)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.