读取VBA中的所有文件夹

时间:2013-07-25 09:15:56

标签: excel-vba vba excel

我在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

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

2 个答案:

答案 0 :(得分:3)

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

要使上面的代码生效,只需将参考(工具 - >参考)添加到 Microsoft Scripting Runtime "。

答案 1 :(得分:1)

您正在尝试将对象绑定到您缺少引用的库。

Dim FSO As Scripting.FileSystemObject

会抛出User-defined type not defined错误

udferror

您需要添加已安装的引用,但不包含在项目Microsoft Scripting Runtime

为此,请选择 Tools » References

references

然后向下滚动,找到并勾选Microsoft Scripting Runtime图书馆

added

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

此外,请注意:您可能需要修改此ListFolders "C:\FolderName\", True行并提供所需路径的路径。