2016-11-23 177 views
1

我已經創建了一個解決方案來循環遍歷路徑中的所有文件夾及其子文件夾,然後根據條件移動文件。循環遍歷文件夾及其子文件夾的特定列表VBA宏

Sub Move_Files_To_Folder() 

Dim Fso As Object, objFolder As Object, objSubFolder As Object 
Dim FromPath As String 
Dim FileInFolder As Object 

FromPath = "C:\Reports\" 
Set Fso = CreateObject("Scripting.filesystemobject") 
Set objFolder = Fso.GetFolder(FromPath) 

For Each objSubFolder In objFolder.subfolders 
    For Each FileInFolder In objSubFolder.Files 

     If InStr(1, FileInFolder.name, ".xlsx") Or InStr(1, FileInFolder.name, ".zip") Then 
      FileInFolder.Move (objSubFolder.Path & "\2016\" & MonthName(Month(FileInFolder.DateCreated)) & "\") 
     End If 

    Next FileInFolder 
Next objSubFolder 

End Sub 

它工作正常,但我想調整我的宏以循環通過我的路徑和所有他們的子文件夾下的特定文件夾。

因此,而不是For Each objSubFolder In objFolder.subfolders我想創建一個數組列表,其中包含我的路徑下的文件夾的名稱來循環。

像這樣的事情

FoldersName = Array("Shipment", "Backlog", "Released", "Unreleased") 
For Each objSubFolder In objFolder.FoldersName 
For Each FileInFolder In objSubFolder.Files 
'rest of my code 
Next FileInFolder 
Next objSubFolder 

所以,作爲一個總結,通過我的路徑下的所有文件夾和子文件夾我的解決方案循環,我想將它調整到我的路徑下的文件夾及其所有子文件夾的列表。

我試圖創建此array並將其添加到For Each但每次我運行我得到該行中的錯誤。任何建議請如何正確寫入?非常感謝你。

回答

1

只需遍歷數組,每次都爲objFolder創建一個新的路徑。 這應該工作:

Sub Move_Files_To_Folder() 

Dim Fso As Object, objFolder As Object, objSubFolder As Object 
Dim FromPath As String 
Dim FileInFolder As Object, i as integer 

FoldersName = Array("Shipment", "Backlog", "Released", "Unreleased") 
FromPath = "C:\Reports\" 
Set Fso = CreateObject("Scripting.filesystemobject") 

for i = 1 to ubound(FoldersName) 

    Set objFolder = Fso.GetFolder(FromPath & FoldersName(i) & "\") 

    For Each objSubFolder In objFolder.subfolders 
    For Each FileInFolder In objSubFolder.Files 

     If InStr(1, FileInFolder.name, ".xlsx") Or InStr(1, FileInFolder.name, ".zip") Then 
      FileInFolder.Move (objSubFolder.Path & "\2016\" & MonthName(Month(FileInFolder.DateCreated)) & "\") 
     End If 

    Next FileInFolder 
Next objSubFolder 
next 

End Sub 
1

您可以使用Dictionary對象(腳本庫),並期待它爲每個子文件夾名稱

Dim dic As Object 
Set dic = CreateObject("Scripting.dictionary") 
For Each word In Array("Shipment", "Backlog", "Released", "Unreleased") 
    dic.Add word, word 
Next 

For Each objSubFolder In objFolder.SubFolders 
    If dic.contains(objSubFolder.Name) Then 
    'etc etc.. 
相關問題