2013-07-25 128 views
3

我把下面的代码放在我的excel中。这是一个脚本,我在网上找到..阅读VBA中的所有文件夹

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 

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

+0

或者只是使用[late binding](http://www.jpsoftwaretech.com/vba/filesystemobject-vba-examples/)代替'FileScriptingObject' – brettdj

回答

3

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

为了使上述工作的代码,只需添加一个引用(工具 - >引用)至Microsoft脚本运行时”。

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行并提供所需路径的路径。

相关问题