是否可以列出一个自定义目录中的所有文件和文件夹 – excel vba

我想知道是否有任何或所有这些function在Excel VBA中是可能的:

  • 列出本地区域内的所有文件夹和子文件夹(path名称)。

  • 生成一个链接,当显示时用户可以从电子表格中打开它。

  • 如果用户添加或删除目录中的任何文件或文件夹/子文件夹,则自动更新电子表格。

我做了一个快速示例,向您展示如何列出所有文件和子文件夹:

Option Explicit Private Sub test() readFileSystem ("C:\Temp\") End Sub Private Sub readFileSystem(ByVal pFolder As String) Dim oFSO As Object Dim oFolder As Object ' create FSO Set oFSO = CreateObject("Scripting.FileSystemObject") ' get start folder Set oFolder = oFSO.getFolder(pFolder) ' list folder content listFolderContent oFolder ' destroy FSO Set oFolder = Nothing Set oFSO = Nothing End Sub Private Sub listFolderContent(ByVal pFolder As Object) Dim oFile As Object Dim oFolder As Object ' go thru all sub folders For Each oFolder In pFolder.SubFolders Debug.Print oFolder.Path ' do the recursion to list sub folder content listFolderContent oFolder Next ' list all files in that directory For Each oFile In pFolder.Files Debug.Print oFile.Path Next ' destroy all objects Set pFolder = Nothing Set oFile = Nothing Set oFolder = Nothing End Sub 

你也可以使用CMD:

 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 

如果你有很多文件,因为它不需要recursion,所以速度要快很多(需要几秒钟才能在一个中等规格的PC上执行超过1000个文件)。

这里是一个例子,如何获得基于Scripting.FileSystemObjectScripting.Dictionary ActiveX的文件夹和文件列表,不需要recursion调用,只有Do ... Loop

 Option Explicit Sub Test() Dim strFolder As String Dim objFolders As Object Dim objFiles As Object Dim i As Long Dim objItem As Object ' target folder strFolder = "C:\Test" ' loop through all folders and files Set objFolders = CreateObject("Scripting.Dictionary") Set objFiles = CreateObject("Scripting.Dictionary") objFolders(0) = strFolder i = 0 With CreateObject("Scripting.FileSystemObject") Do With .GetFolder(objFolders(i)) For Each objItem In .Files objFiles(objFiles.Count) = objItem.Path Next For Each objItem In .SubFolders objFolders(objFolders.Count) = objItem.Path Next End With i = i + 1 Loop Until i = objFolders.Count End With ' results output to the 1st sheet With Sheets(1) .Select .Cells.Delete .Range(.Cells(1, 1), .Cells(objFolders.Count, 1)).Value = Application.Transpose(objFolders.Items) .Range(.Cells(1, 2), .Cells(objFiles.Count, 2)).Value = Application.Transpose(objFiles.Items) .Columns.AutoFit End With End Sub