Read file names into a directory and randomly copy them

User avatar
Abraxus
3StarLounger
Posts: 263
Joined: 01 Mar 2010, 17:34
Location: Blue Springs, MO

Read file names into a directory and randomly copy them

Post by Abraxus »

I have a directory of files.

I need to copy those files into a different directory in a random order. (don't ask...)

My best guess on how to do it is to read the file names into an array, then randomize that array, then copy the files, but I don't know how...

Any suggestions on the randomizing the array part?

Thanks!
Morgan

User avatar
HansV
Administrator
Posts: 79365
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Read file names into a directory and randomly copy them

Post by HansV »

Try something like this:

Code: Select all

Sub RandomizeFiles()
  ' Modify as needed
  Const strSourceFolder = "C:\Test"
  Dim fso As Object
  Dim fld As Object
  Dim fil As Object
  Dim arrNames() As String
  Dim i As Long
  Dim j As Long
  Dim m As Long
  Dim n As Long
  Dim t As String
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set fld = fso.GetFolder(strSourceFolder)
  n = fld.Files.Count
  ' Fill array with file names
  ReDim arrNames(1 To n)
  i = 0
  For Each fil In fld.Files
    i = i + 1
    arrNames(i) = fil.Name
  Next fil
  ' Shuffle the list 4 times
  Randomize
  For m = 1 To 4
    For i = 1 To n
      j = Int(Rnd * n + 1)
      t = arrNames(i)
      arrNames(i) = arrNames(j)
      arrNames(j) = t
    Next i
  Next m
  ' Your code goes here
  ...
End Sub
Best wishes,
Hans

User avatar
Abraxus
3StarLounger
Posts: 263
Joined: 01 Mar 2010, 17:34
Location: Blue Springs, MO

Re: Read file names into a directory and randomly copy them

Post by Abraxus »

That worked perfectly, thank you!

Definitely a piece of keeper code.
Morgan

kwvh
3StarLounger
Posts: 308
Joined: 24 Feb 2010, 13:41

Re: Read file names into a directory and randomly copy them

Post by kwvh »

Could this code be modified to read a directory on an ftp server? Not cross posting or double posting, but would like to do something like this to read the files in a directory on an ftp server into a field in a table and compare the results with the files in a local directory.

Thanks!

Ken

User avatar
HansV
Administrator
Posts: 79365
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Read file names into a directory and randomly copy them

Post by HansV »

Sorry, I can't help you with that.
Best wishes,
Hans