Excel 在VBA中读取所有文件夹

Excel 在VBA中读取所有文件夹,excel,vba,Excel,Vba,我在excel中输入了以下代码。这是我在网上找到的一个脚本 Sub TestListFolders() Application.ScreenUpdating = False Workbooks.Add ' create a new workbook for the folder list ' add headers With Range("A1") .Formula = "Folder contents

我在excel中输入了以下代码。这是我在网上找到的一个脚本

   Sub TestListFolders()
        Application.ScreenUpdating = False
        Workbooks.Add ' create a new workbook for the folder list
        ' add headers
        With Range("A1")
            .Formula = "Folder contents:"
            .Font.Bold = True
            .Font.Size = 12
        End With
        Range("A3").Formula = "Folder Path:"
        Range("B3").Formula = "Folder Name:"
        Range("C3").Formula = "Size:"
        Range("D3").Formula = "Subfolders:"
        Range("E3").Formula = "Files:"
        Range("F3").Formula = "Short Name:"
        Range("G3").Formula = "Short Path:"
        Range("A3:G3").Font.Bold = True
        ListFolders "C:\FolderName\", True
        Application.ScreenUpdating = True
    End Sub

Sub ListFolders(SourceFolderName As String, IncludeSubfolders As Boolean)
' lists information about the folders in SourceFolder
' example: ListFolders "C:\FolderName", True
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.Folder, SubFolder As Scripting.Folder
Dim r As Long
    Set FSO = New Scripting.FileSystemObject
    Set SourceFolder = FSO.GetFolder(SourceFolderName)
    ' display folder properties
    r = Range("A65536").End(xlUp).Row + 1
    Cells(r, 1).Formula = SourceFolder.Path
    Cells(r, 2).Formula = SourceFolder.Name
    Cells(r, 3).Formula = SourceFolder.Size
    Cells(r, 4).Formula = SourceFolder.SubFolders.Count
    Cells(r, 5).Formula = SourceFolder.Files.Count
    Cells(r, 6).Formula = SourceFolder.ShortName
    Cells(r, 7).Formula = SourceFolder.ShortPath
    If IncludeSubfolders Then
        For Each SubFolder In SourceFolder.SubFolders
            ListFolders SubFolder.Path, True
        Next SubFolder
        Set SubFolder = Nothing
    End If
    Columns("A:G").AutoFit
    Set SourceFolder = Nothing
    Set FSO = Nothing
    ActiveWorkbook.Saved = True
End Sub
脚本失败,因为我缺少此对象

New Scripting.FileSystemObject

如何获取对象的库?是否有另一个不依赖于该对象的脚本可供我使用?

VBA本身具有访问文件系统的内置函数(例如,
Dir
),但它们使用起来非常不方便


要使上述代码正常工作,只需向Microsoft脚本运行时添加一个引用(工具->引用)。

您正试图将一个对象绑定到缺少引用的库

这个

将抛出一个
未定义的用户定义类型
错误

您需要添加对已安装但未包含在project
Microsoft脚本运行时库中的引用

为此,请选择工具

然后向下滚动,找到并勾选Microsoft脚本运行时库

现在,重新运行您的过程,一切都应该按预期工作

此外,请注意:您可能需要编辑此
列表文件夹“C:\FolderName\”,True
行,并提供所需路径的路径。

或只用于
文件脚本对象
Dim FSO As Scripting.FileSystemObject