2013-11-14 59 views
2

我有以下代碼,我想要獲取水平列出的各種文件夾中的文件。我該如何修改這段代碼,以便對列A中給定的文件路徑,我得到列C中此列中的文件?我的知識只允許我做一個文件夾(而不是150我希望它看起來在)VBA宏列出多個文件夾中的文件


`enter code here` 
Sub ListFiles() 
    iCol = 3 
    Call ListMyFiles(Range("A5"), Range("B5")) 
End Sub 

Sub ListMyFiles(mySourcePath, IncludeSubfolders) 
    Set MyObject = New Scripting.FileSystemObject 
    Set mySource = MyObject.GetFolder(mySourcePath) 
    On Error Resume Next 
    For Each myFile In mySource.Files 
     iRow = 5 

     Cells(iRow, iCol).Value = myFile.Name 
     iCol = iCol + 1 

    Next 
    If IncludeSubfolders Then 
     For Each mySubFolder In mySource.SubFolders 
      Call ListMyFiles(mySubFolder.Path, True) 
     Next 

    End If 
End Sub 
+0

這是非常簡單的(只需把'iCol'放在有'iRow'的地方,反之亦然;'Cells(iRow,iCol).Value'除外)。你應該嘗試過一些東西;並且顯示「之前」聽起來並沒有嘗試任何事情。 – varocarbas

回答

0
'it's all in iRow 
`enter code here` 
Dim iRow as integer 
Sub ListFiles() 
    iCol = 3 
    iRow = 5 
    Call ListMyFiles(Range("A5"), Range("B5")) 
End Sub 

Sub ListMyFiles(mySourcePath, IncludeSubfolders) 
    Set MyObject = New Scripting.FileSystemObject 
    Set mySource = MyObject.GetFolder(mySourcePath) 
    On Error Resume Next 
    For Each myFile In mySource.Files 


     Cells(iRow, iCol).Value = myFile.Name 
     iCol = iCol + 1    
    Next 
    iRow = iRow + 1 
    If IncludeSubfolders Then 
     For Each mySubFolder In mySource.SubFolders 
      Call ListMyFiles(mySubFolder.Path, True) 
     Next 

    End If 
End Sub 
+0

在回答之前,你應該看看評論/其他答案。如果你有不同的想法,並決定繼續爲OP寫代碼;你至少應該從這些其他答案中提取儘可能多的信息;並確保你的答案是正確的。請測試你的代碼並確認它沒有提供OP想要的內容;我建議你在我的評論中遵循適應症。 – varocarbas

+0

迷失了我,當我對他們的代碼做了一個非常小的更正時,您的評論並不存在,並感謝您的建議! –

1

我在Excel 2007中測試了這個:

Sub ListMyFiles(mySourcePath, IncludeSubfolders, iRow, iCol) 
    Dim iColNow, iColSub 
    Dim MyObject, mySource, myFile, mySubFolder 
    Set MyObject = CreateObject("Scripting.FileSystemObject") 
    Set mySource = MyObject.GetFolder(mySourcePath) 
    On Error Resume Next 
    iColNow = iCol 
    For Each myFile In mySource.Files 
    Cells(iRow, iColNow).Value = myFile.Name 
    iColNow = iColNow + 1 
    Next 
    If IncludeSubfolders Then 
    ' 
    'iColSub = iCol + 1 
    ' 
    iColSub = iCol 
    For Each mySubFolder In mySource.SubFolders 
     iRow = iRow + 1 
     Call ListMyFiles(mySubFolder.Path, IncludeSubfolders, iRow, iColSub) 
    Next 
    End If 
End Sub 

Sub ListFiles() 
    Dim iRow, iCol 
    iRow = 5 
    iCol = 3 
    Call ListMyFiles(Range("A5"), Range("B5"), iRow, iCol) 
End Sub 

IRow和iCol是控制結果輸出起始位置的函數參數。 Range(「A5」)給出起始文件夾名稱,如C:\ temp,Range(「B5」)是子文件夾列表控制鍵,1 = true,0 = false。

enter image description here ========>

enter image description here

空白行將與文件條目的文件夾中創建。

爲了更改每個子文件夾的行,遞歸修改iRow。

相關問題