如何避免重置Dir?
d = Dir(root & "*", vbDirectory)
d = Dir(): d = Dir() ' skip . and ..
While d <> ""
f = Dir(root & d & "\*.txt")
While f <> ""
' do something with f
f = Dir()
Wend
d = Dir() ' RunTime Error "5": Invalid Procedure or Call to Argument
Wend
我的理解是,当Dir(root & d & "\*.txt")
被调用时,Dir(root & "*", vbDirectory)
生成的第一个列表被重置。我怎么能避免这个?我尝试将第二个循环放在函数
d = Dir(root & "*", vbDirectory)
d = Dir(): d = Dir() ' skip . and ..
While d <> ""
f = Dir(root & d & "\*.txt")
call foo(root & d)
d = Dir() ' RunTime Error "5": Invalid Procedure or Call to Argument
Wend
希望内部Dir调用超出范围但会引发相同的错误。
有没有办法安全地循环Dir
而不用担心在该循环中调用的函数也可能调用Dir
并破坏列表?
注意:
我知道“Scripting.FileSystemObject”但是如果可能的话我想避免使用它。
答案 0 :(得分:3)
使用集合来缓存第一个Dir()循环的结果:然后对每个项目运行第二个循环:
Sub Traverse()
Dim col As New Collection, fpath, f, d, root
root = "C:\_stuff\test\"
d = Dir(root, vbDirectory)
Do While d <> ""
If (GetAttr(root & d) And vbDirectory) <> 0 Then
If d <> "." And d <> ".." Then col.Add root & d
End If
d = Dir()
Loop
For Each fpath In col
f = Dir(fpath & "\*.txt")
While f <> ""
'do something with f
f = Dir()
Wend
Next
End Sub