【发布时间】:2017-01-20 20:52:01
【问题描述】:
这是我第一次发帖,如有错误请见谅。
我正在尝试通过服务器文件夹(UNC 路径)循环查找特定的子文件夹(项目文件夹)来保存工作簿(用户将通知与该文件夹相关的项目)。
我正在使用循环和 DIR() 函数,但由于某种原因 DIR() 返回“。”第一个文件夹循环,第二个循环返回第一个子文件夹。
StdPath = "\\Server\Database$\ABC\"
'Find project folder
Dirloop1 = Dir(StdPath, vbDirectory) 'Should return the 1st child folder, instead returns "."
'Loop into folders until find the project folder speficied by the user
Do Until Dirloop1 = ""
If (GetAttr(StdPath & Dirloop1) And vbDirectory) = vbDirectory Then
Dirloop2 = Dir(StdPath & Dirloop1, vbDirectory) 'This should indicate the 2nd child folder but instead is returning the 1st child folder
Do Until Dirloop2 = ""
If (GetAttr(StdPath & Dirloop1 & Dirloop2) And vbDirectory) = vbDirectory Then 'Error happens here since it didn't reach the second child folder
If InStr(Dirloop2, ActiveSheet.Range("N7")) > 0 Then
StdPath = StdPath & Dirloop1 & Dirloop2
MsgBox StdPath
Exit Do
Else
Dirloop2 = Dir()
End If
End If
Loop
If InStr(StdPath, ActiveSheet.Range("N7")) = 0 Then
Exit Do
End If
End If
Dirloop1 = Dir()
Loop
这是我第一次使用编程,因此没有太多经验,如果有人可以给我更好的解决方案,我感谢支持。
【问题讨论】:
-
您应该检查并忽略这两个“。”并返回“..”。
-
你的意思是用 DIR 语句做一个 while 语句,直到返回正确的文件夹?
-
不,您只需要在开始搜索子文件夹之前进行
If dirloop1 <> "." and dirloop1 <> ".." then测试。与dirloop2相同。 -
Dir只能同时保持一个状态——你不能这样嵌套它。考虑改用Scripting.FileSystemObject。此外,.是 一个(虚拟)文件夹 - 它指向父目录。
标签: excel loops directory unc vba