Home » excel » excel – Is it possible so that this code gets files aswell as folders?

excel – Is it possible so that this code gets files aswell as folders?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I currently have this code:

Function GetSubDir(ByVal sDir)

Dim oFS As New FileSystemObject
Dim oDir
iCount = 1
Erase subArray()
Set oDir = oFS.GetFolder(sDir)
For Each oSub In oDir.SubFolders
    MsgBox oSubPath
    GetSubDir oSub.Path
    ReDim Preserve subArray(iCount)
    subArray(iCount) = oSub.Path
    iCount = iCount + 1
Next oSub

End Function

Is there a way to modify it so that it gets files AND folders? I have tried looking at MSDN however it’s pretty foreign to me, is it a simple syntax change or would the whole code require a rework? Thanks

How to&Answers:

I think it’s quite possible – this sample code shows how to cycle files:

Sub ShowFileList(folderspec)
    Dim fs, f, f1, fc, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.Files
    For Each f1 in fc
        s = s & f1.name 
        s = s &  vbCrLf
    Next
    MsgBox s
End Sub

Simply you need to add one more For...Each cycle. However, if you want to recursively process all the files and all subfolders to the last deep level – this will require some more coding. However, plenty of such ready-to-go snippets may be revealed using Google in a matter of minutes. Good luck!

Answer:

Function GetSubDir(ByVal sDir)

Dim oFS As New FileSystemObject

Dim oDir
Dim oSub As Object
Dim i As Integer

Dim wbName As String

Set oDir = oFS.GetFolder(sDir)
For Each oSub In oDir.SubFolders
    SDCount = SDCount + 1
    ReDim Preserve wbSDName(1 To SDCount)
    wbSDName(SDCount) = oSub.Path
    GetSubDir oSub.Path
Next oSub

End Function