1

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.

Payam Mesgari
  • 953
  • 1
  • 19
  • 38
  • Are you copying the file to the same directory? – Barney Jan 05 '17 at 15:07
  • copyFile is just a module, I do other stuff in there as well. The point is the argument to the copyFile module suddenly gets incremented by one. In principle copyFile can be any other module, not even performing a copy action. – Payam Mesgari Jan 05 '17 at 15:10
  • Can you try with the code from here: http://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba – Vityata Jan 05 '17 at 15:13
  • Probably not the issue here, but remove the parentheses when you're calling a `Sub` procedure. You want `copyFile file`, not `copyFile (file)`. The parentheses are merely passing the string `ByVal` to the `copyFile` procedure, and that will eventually bite you in the rear end when you try to pass object variables around like that. – Mathieu Guindon Jan 05 '17 at 15:13
  • 2
    Actually the problem is that with `file=Dir` you change the file to the new one. That is why it is happening. Put the `file=Dir` before the `Loop`. It should work. – Vityata Jan 05 '17 at 15:14
  • 1
    "file here is also correct" - certainly you mean *before* the assignment. You're re-assigning `file` before you call `copyFile`, so the value you're printing isn't going to be the one you copy. Move `file = Dir` *after* the `copyFile file` call. You could probably benefit learning to use breakpoints (F9), step-through (F8) and the *locals* debugger toolwindow. – Mathieu Guindon Jan 05 '17 at 15:15

1 Answers1

2

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?

Community
  • 1
  • 1
Vityata
  • 42,633
  • 8
  • 55
  • 100