简体   繁体   中英

Loop through files in directory VBA

I am looping through files in one directory, it all works fine but it gets strange when I pass the file to another function in the module. It skips the first file retrieved in the loop! Let's say the first loop run for example file is "File1" but once it hits copyFile (file) then it passes "File2" to the function, which also exists, for some reason it increments the loop automatically on calling the copyFile function.

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

I have tried defining a string, storing file in there and then pass it to copyFile(stringFile) but the same happens.

Can you try like this:

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

I think that it should be working. Take a look at the code here as well: Loop through files in a folder using VBA?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM