Is it possible to list all the files and folders in a custom directory - excel vba

前端 未结 4 1857
别跟我提以往
别跟我提以往 2020-12-06 15:07

I wanted to know whether any or all of these functions are possible in excel VBA or not:

  • List all the folders and sub folders within a local area (path name

4条回答
  •  鱼传尺愫
    2020-12-06 16:00

    You could use CMD too:

    Sub MM()
    
    Dim fileResults As Variant
    
    fileResults = GetFiles("C:\Users\Macro Man\Documents")
    
    Range("A1").Resize(UBound(fileResults) + 1, 1).Value = _
        WorksheetFunction.Transpose(fileResults)
    
    End Sub
    
    
    '// UDF to populate array with files, assign to a Variant variable. 
    Function GetFiles(parentFolder As String) As Variant
    
    GetFiles = Filter(Split(CreateObject("WScript.Shell").Exec("CMD /C DIR """ & parentFolder & _
        IIf(Right(parentFolder, 1) = "\", vbNullString, "\") & "*.*"" /S /B /A:-D").StdOut.ReadAll, vbCrLf), ".")
    
    End Function
    

    This is a lot quicker (takes a couple of seconds to do 1000+ files on a moderate spec PC) if you have lots of files as it doesn't need recursion.

提交回复
热议问题