循环遍历目录VBA中的文件

时间:2017-01-05 14:54:51

标签: vba directory do-while

我在一个目录中循环浏览文件,一切正常,但是当我将文件传递给模块中的另一个函数时会很奇怪。它会跳过循环中检索到的第一个文件! 我们假设第一个循环运行,例如file"File1"但是一旦它命中copyFile (file),它就会将"File2"传递给该函数,该函数也存在,对于某些因为它在调用copyFile函数时自动递增循环。

Dim file As Variant
file = Dir("PATH TO MY DIRECTORY")
Do While Len(file) > 0
    Debug.Print file  'Here the right name is printed
    file = Dir 'file here is also correct, at the beginning of the loop it shows File1 
    copyFile (file) 'Here suddenly the next file is sent to the copyFile

Loop

我尝试过定义一个字符串,在其中存储file,然后将其传递给copyFile(stringFile),但同样的情况也会发生。

1 个答案:

答案 0 :(得分:2)

你可以尝试这样:

Dim file As Variant
file = Dir("PATH TO MY DIRECTORY")
Do While Len(file) > 0
    Debug.Print file  'Here the right name is printed
    copyFile (file) 'Here suddenly the next file is sent to the copyFile
    file = Dir 
Loop

我认为应该有效。看看这里的代码: Loop through files in a folder using VBA?