문제

How can I avoid resetting 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

My understanding is when Dir(root & d & "\*.txt") is called, the first list generated by Dir(root & "*", vbDirectory) is reset. How can I avoid this? I tried placing the second loop in a function

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

hoping that the inner Dir call would be out of scope but it raises the same error.

Is there any way to safely loop with Dir without worrying that functions called in that loop might also call Dir and ruin the list?

Note:

I am aware of "Scripting.FileSystemObject" but would like to avoid it if possible.

도움이 되었습니까?

해결책

Use a collection to cache results from your first Dir() loop: then run your second loop on each of those items:

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top