need vbscript code to choose a random file in a directory

Bozz

Senior member
Jun 27, 2001
918
0
0
I need some code that will choose a random file in a preset directory. I've googled for it and I can't find anything that would suit.

Would this be the flow to code a random file selector: ?

-Open a directory as an array (eg fso.getfolder("c:\folder"))

-count how many objects in the array

-generate a random number between zero and 1 and multiply it by the amount of objects in the array, and add 1

-open the file number from the above result



Anyone got any better methods?
 

KB

Diamond Member
Nov 8, 1999
5,406
389
126
Thats how I would do it!

Dim fs, f, f1, fc, s

Set fs = CreateObject("Scripting.FileSystemObject")

Set f = fs.GetFolder("C:\")

Randomize
i = CInt((Rnd() * f.Files.Count) + 1)
j = 1


For Each fi In f.Files

If j >= i Then
MsgBox fi.Name
Exit For
End If
j = j + 1
Next
 

Bozz

Senior member
Jun 27, 2001
918
0
0
Sweet, thank you very much, especially for the code, saved me perhaps an hour writing and debugging it :)

On that topic, I'm OK with vb scripting, basically learned from the MS scripting docs, are there any recommended sites to get better and understand the concepts more thoroughly?