Search code examples
arraysfilevbscriptappendhta

Load all files within a folder into an array with vbscript / hta?


I want to load all files of a directory into an array with vbscipt/hta in order to sort and "call" them later by index. I've tried something like this, but it's not working:

Set objFSO = CreateObject("Scripting.FileSystemObject")

objFileFolder = "C:\"

Set objFolder = objFSO.GetFolder(objFileFolder)
Set colFiles = objFolder.Files


dim arrFileList()

For Each objFile in colFiles
ReDim Preserve arrFileList(UBound(arrFileList) + 1)
FileList(UBound(arrFileList)) = objFile.Name    
Next

I'd be grateful for any help! THX in advance


Solution

  • You need to change two things, please see new code below. Comments in line.

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    
    objFileFolder = "C:\"
    
    Set objFolder = objFSO.GetFolder(objFileFolder)
    Set colFiles = objFolder.Files
    
    
    dim arrFileList()
    ReDim Preserve arrFileList(0) 'If you wish to use the array UBound later on you must redim this here
    
    For Each objFile in colFiles
      ReDim Preserve arrFileList(UBound(arrFileList) + 1)
      arrFileList(UBound(arrFileList)) = objFile.Name    ' Here you were calling FileList, not arrFileList
    Next
    

    You could further tidy / improve this code as arrFileList(0) will have no value upon finishing.