2016-07-18 54 views
0

我有200個文件夾中的所有文件夾中都有不同的名稱。現在,每個名稱不同的文件夾都有一個宏Excel文件(.xlsm)。我試圖用一個單獨的文件一次編輯所有文件。代碼如下所示:編輯不同文件夾中的多個excel文件全部合併到一個文件夾中

Sub Button1_Click() 

Dim wb  As Workbook 
Dim ws  As Excel.Worksheet 
Dim strPath As String 
Dim strFile As String 

'Get the directories 
strPath = "C:\Users\generaluser\Desktop\testing main folder\" 
strFile = Dir(strPath) 

'Loop through the dirs 
Do While strFile <> "" 

    'Open the workbook. 
    strFileName = Dir(strPath & strFile & "*.xlsm") 
    'Open the workbook. 
    Set wb = Workbooks.Open(Filename:=strPath & strFile & "\" & strFileName , ReadOnly:=False) 

    'Loop through the sheets. 

    Set ws = Application.Worksheets(1) 

    'Do whatever 
    ws.Range("A1").Interior.ColorIndex = 0 



    'Close the workbook 
    wb.Close SaveChanges:=True 

    'Move to the next dir. 
    strFile = Dir 
Loop 

End Sub 

但這不起作用。我試過調整它,但無論我做什麼都不做或導致錯誤。有人可以幫助我讓這個代碼工作。 (另外:「測試主文件夾」是我的桌面上的文件夾,用於保存包含200個其他文件夾的.xlsm文件。)

+0

[這個答案](http://stackoverflow.com/questions/22645347/loop-through-all-subfolders-using-vba)將幫助你瞭解如何遍歷子文件夾。 –

+1

[循環通過用戶指定的根目錄中的子文件夾和文件]可能的重複(http://stackoverflow.com/questions/14245712/cycle-through-sub-folders-and-files-in-a-user -specified-root-directory) – Comintern

回答

0

Option Explicit置於模塊的頂部。你會得到一些編譯器錯誤,其中之一是strFileName未被聲明。這個一直是一個很好的線索,因爲問題在於,當你閱讀它們時,你使用了兩個具有大致相同含義的變量名,並且它們變得混雜起來。

完成修改變量後,請查看Dir function的文檔。第二個問題是你也在循環中多次呼叫Dir,這意味着你正在跳過結果。

它應該看起來更像是這樣的:

Dim wb As Workbook 
Dim ws As Excel.Worksheet 
Dim file As String 

'path never changes, so make it a Const 
Const path = "C:\Users\generaluser\Desktop\testing main folder\" 
'This returns the first result. 
file = Dir$(path & "*.xlsm") 

Do While file <> vbNullString 
    Set wb = Workbooks.Open(Filename:=path & file, ReadOnly:=False) 
    Set ws = Application.Worksheets(1) 
    'Do whatever 
    wb.Close SaveChanges:=True 
    'This returns the next result, or vbNullString if none. 
    file = Dir$ 
Loop 
+0

這仍然不能打開**子文件夾中的'.xlsm'文件** –

+0

@ScottHoltzman - 我沒有看到關於子文件夾的任何問題,但瞭解如何迭代一個目錄是無疑是邁向正確方向的一步。 – Comintern

+0

重讀前兩句話的問題 –

相關問題