2013-07-25 195 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行並提供所需路徑的路徑。

相關問題