Search code examples
excelvba

return multiple values function


I need to get some information about some files so im trying to build a function that returns 3 information like this:

sub main()
    File = getFile(path) 'future code to list all file information on range

end sub


Function getFile(ByVal path as String)

Dim result() as String
Dim Arquivo as File

Set Folder = FSO.getFolder(Path)

For Each File in Folder.Files
    result(n) = File.Name
    result2(n) = File.DateLastModified
    result3(n) = File.ParentFolder
Next    

getFile = Result(), Result2(),Result3()???

End function

Is it possible to return the 3 file information in a single funcion?


Solution

  • Please, try the next adapted function:

    Function getFile(ByVal path As String) As Variant
     Dim fso As Object, folder As Object, file As Object
     Dim arrName, arrDat, arrPar, n As Long
    
     Set fso = CreateObject("Scripting.FileSystemObject")
     Set folder = fso.GetFolder(path)
     ReDim arrName(folder.files.count - 1)
     ReDim arrDat(folder.files.count - 1)
     ReDim arrPar(folder.files.count - 1)
    
     For Each file In folder.files
        arrName(n) = file.name
        arrDat(n) = file.DateLastModified
        arrPar(n) = file.parentfolder
        n = n + 1
     Next
     getFile = Array(arrName, arrDat, arrPar)
    End Function
    

    It can be tested in the next way:

    Sub main()
       Dim file As Variant, path As String
       
       path = "the folder path" 'please use here a real path...
       file = getFile(path) 'future code to list all file information on range
        Debug.Print file(0)(0), file(1)(0), file(2)(0)
    End Sub