2017-07-06 307 views
0

我有77個工作簿,需要將工作表3全部合併到新工作簿中的一個工作表中。我好幾年沒有這樣做過。我會很感激任何幫助。我修改了其他網頁的一些代碼,但它不適合我。將來自多個工作簿的工作表3合併到一個新工作簿中

謝謝,男

+0

是否在一個文件夾中處理所有工作簿? –

+0

你好,是的,我已經爲我正在使用的77個縣創建了一個文件夾,並且我已經在同一個文件夾中創建了一個MergedCO工作簿 – MaryGM

回答

0

這裏是我有,你能滿足你的需要

Sub ConslidateWorkbooks() 
    'Code to pull sheets from multiple Excel files in one file directory 
    'into master "Consolidation" sheet. 

    Dim FolderPath As String 
    Dim Filename As String 
    Dim Sheet As Worksheet 

    Application.ScreenUpdating = False 
    FolderPath = "[REDACTED]" 
    Filename = Dir(FolderPath & "*.xlsx") 

    Do While Filename <> "" 
     Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True 
     copyOrRefreshSheet ThisWorkbook, Sheets(3) 
     Workbooks(Filename).Close 
     Filename = Dir() 
    Loop 

    Application.ScreenUpdating = True 

End Sub 



Sub copyOrRefreshSheet(destWb As Workbook, sourceWs As Worksheet) 
    Dim ws As Worksheet 
    On Error Resume Next 
    Set ws = destWb.Worksheets(sourceWs.Name) 
    On Error GoTo 0 
    If ws Is Nothing Then 
     sourceWs.Copy After:=destWb.Worksheets(destWb.Worksheets.Count) 
    Else 
     ws.Cells.ClearContents 
     ws.Range(sourceWs.UsedRange.Address).Value = sourceWs.UsedRange.Value2 
    End If 
End Sub 

它可能無法正常工作完美,但它應該指向你在正確的道路上

+0

在循環中間,「下一張」表示什麼? – Masoud

+0

對不起,我錯過了。我有另一個宏將所有工作簿中的所有工作表複製到特定文件夾中。我稍微編輯了這個,以便它符合OP的規範,但我忘了拿出那條線。現在編輯。 –

+0

是的,我知道:https://www.extendoffice.com/documents/excel/456-combine-multiple-workbooks.html和 – Masoud

1

如果他們都在一個文件夾中,那麼這個工作:

Sub CopySheetsOver() 
Dim Path As String, Filename As String 
Dim wbk As Workbook 
Dim wsh As Worksheet 

Path = "C:\Users\MaryGM\Desktop\YourFolder\" 'set the path to the desired folder 
Filename = Dir(Path & "*.xls") 'get names of all xls files, change to xlsx if desired 

Do While Filename <> "" 'loop over all the xlsx files in that folder 
    Workbooks.Open Filename:=Path & Filename, ReadOnly:=True 

    Set wbk = ActiveWorkbook 
    If wbk.Worksheets.Count > 2 Then 'check if the third sheet exists 
    Set wsh = wbk.Sheets(3) 
    wsh.Copy After:=ThisWorkbook.Sheets(1) 
    'set the name to be combination of original sheet name and its corresponding workbook: 
    ThisWorkbook.ActiveSheet.Name = wbk.Name & "-" & wsh.Name 
    End If 
    Workbooks(Filename).Close 
    Filename = Dir() 
Loop 
End Sub 
+0

非常感謝!所需文件夾的路徑是我想要的表格,對吧?所需的文件夾將是我想要包含的所有內容,對吧? – MaryGM

+0

它給運行時錯誤1004應用程序定義或對象定義 – MaryGM

+0

@MaryGM突出顯示哪一行 – Masoud

相關問題