在 VBA 中保留目录列表

che*_*eak 0 vba scope dir

如何避免重置 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
Run Code Online (Sandbox Code Playgroud)

我的理解是当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
Run Code Online (Sandbox Code Playgroud)

希望内部 Dir 调用超出范围,但它会引发相同的错误。

有没有什么方法可以安全地循环,而Dir不用担心在该循环中调用的函数也可能调用Dir并破坏列表?

笔记:

我知道“Scripting.FileSystemObject”,但希望尽可能避免它。

Tim*_*ams 5

使用集合来缓存第一个 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
Run Code Online (Sandbox Code Playgroud)