Question

I'm trying to access a file by index using vbs but Item does not work as I expected. I would rather not have to loop all files as I'm trying to avoid a treewalk. I recieve the error "Error: Invalid procedure call or argument" on the line with colFiles.Item().

Randomize
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(fFolder.Path)
Set colFiles = objFolder.Files
Set objFile = colFiles.Item(Int(colFiles.Count * Rnd))

I'm sure it's obvious, but my searching only shows example using loops.

Was it helpful?

Solution

VBScript does not support random/index access to the elements of the .Files collection. You'll have to For Each loop, pick a random file, and Exit the loop.

Update:

According to the docs, you can use a 'name' (file name, file spec(?)) as parameter to .Item(), so you could keep an array of file names/specs, pick one randomly, and access the file. Whether that would be an improvement in your case, remains to be seen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top