3

我将以下代码放入我的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

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

4

2 回答 2

3

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

要使上述代码正常工作,只需向Microsoft Scripting Runtime添加一个引用( Tools->References)。

于 2013-07-25T09:21:13.587 回答
1

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

Dim FSO As Scripting.FileSystemObject

会抛出一个User-defined type not defined错误

错误

您需要添加对已安装但未包含在项目Microsoft Scripting Runtime库中的引用

为此,请选择Tools»References

参考

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

添加

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

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

于 2013-07-25T09:42:03.077 回答