跳到主要內容

如何遍歷目錄中的文件並將數據複製到Excel中的主表中?

假設一個文件夾中有多個Excel工作簿,並且您想循環瀏覽所有這些Excel文件,並將數據從指定範圍的同名工作表中復製到Excel中的主工作表中,該怎麼辦? 本文詳細介紹了一種實現方法。

循環瀏覽目錄中的文件,然後使用VBA代碼將數據複製到主表中


循環瀏覽目錄中的文件,然後使用VBA代碼將數據複製到主表中

如果要將範圍A1:D4中的指定數據從某個文件夾中的所有工作簿工作表1複製到母版工作表,請執行以下操作。

1.在工作簿中,您將創建一個主工作表,然後按 其他 + F11 鍵打開 Microsoft Visual Basic for Applications 窗口。

2。 在裡面 Microsoft Visual Basic for Applications 窗口中,單擊 插入 > 模塊。 然後將下面的VBA代碼複製到代碼窗口中。

VBA代碼:循環瀏覽文件夾中的文件並將數據複製到主表中

Sub Merge2MultiSheets()
    Dim xRg As Range
    Dim xSelItem As Variant
    Dim xFileDlg As FileDialog
    Dim xFileName, xSheetName, xRgStr As String
    Dim xBook, xWorkBook As Workbook
    Dim xSheet As Worksheet
    On Error Resume Next
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    Application.ScreenUpdating = False
    xSheetName = "Sheet1"
    xRgStr = "A1:D4"
    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    With xFileDlg
        If .Show = -1 Then
            xSelItem = .SelectedItems.Item(1)
            Set xWorkBook = ThisWorkbook
            Set xSheet = xWorkBook.Sheets("New Sheet")
            If xSheet Is Nothing Then
                xWorkBook.Sheets.Add(after:=xWorkBook.Worksheets(xWorkBook.Worksheets.Count)).Name = "New Sheet"
                Set xSheet = xWorkBook.Sheets("New Sheet")
            End If
            xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
            If xFileName = "" Then Exit Sub
            Do Until xFileName = ""
               Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)
                Set xRg = xBook.Worksheets(xSheetName).Range(xRgStr)
                xRg.Copy xSheet.Range("A65536").End(xlUp).Offset(1, 0)
                xFileName = Dir()
                xBook.Close
            Loop
        End If
    End With
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

備註:

1)。 在代碼中,“A1:D4“和”Sheet1”表示將所有Sheet1的A4:D1範圍內的數據複製到主表中。 還有“新表”是新創建的母版表的名稱。
2)。 特定文件夾中的Excel文件不應打開。

3。 按 F5 鍵來運行代碼。

4.在開幕 瀏覽 窗口,請選擇包含您要循環瀏覽的文件的文件夾,然後單擊 OK 按鈕。 看截圖:

然後,在當前工作簿的末尾創建一個名為“ New Sheet”的主工作表。 工作表中列出了所選文件夾中所有Sheet1的A4:D1範圍內的數據。


相關文章:

最佳辦公生產力工具

🤖 Kutools 人工智慧助手:基於以下內容徹底改變數據分析: 智慧執行   |  生成代碼  |  建立自訂公式  |  分析數據並產生圖表  |  呼叫 Kutools 函數...
熱門特色: 尋找、突出顯示或識別重複項   |  刪除空白行   |  合併列或儲存格而不遺失數據   |   沒有公式的回合 ...
超級查詢: 多條件VLookup    多值VLookup  |   跨多個工作表的 VLookup   |   模糊查詢 ....
高級下拉列表: 快速建立下拉列表   |  依賴下拉列表   |  多選下拉列表 ....
欄目經理: 新增特定數量的列  |  移動列  |  切換隱藏列的可見性狀態  |  比較範圍和列 ...
特色功能: 網格焦點   |  設計圖   |   大方程式酒吧    工作簿和工作表管理器   |  資源庫 (自動文字)   |  日期選擇器   |  合併工作表   |  加密/解密單元格    按清單發送電子郵件   |  超級濾鏡   |   特殊過濾器 (過濾粗體/斜體/刪除線...)...
前 15 個工具集12 文本 工具 (添加文本, 刪除字符,...)   |   50+ 圖表 類型 (甘特圖,...)   |   40+ 實用 公式 (根據生日計算年齡,...)   |   19 插入 工具 (插入二維碼, 從路徑插入圖片,...)   |   12 轉化 工具 (數字到單詞, 貨幣兌換,...)   |   7 合併與拆分 工具 (高級合併行, 分裂細胞,...)   |   ... 和更多

使用 Kutools for Excel 增強您的 Excel 技能,體驗前所未有的效率。 Kutools for Excel 提供了 300 多種進階功能來提高生產力並節省時間。  點擊此處獲取您最需要的功能...

產品描述


Office選項卡為Office帶來了選項卡式界面,使您的工作更加輕鬆

  • 在Word,Excel,PowerPoint中啟用選項卡式編輯和閱讀,發布者,Access,Visio和Project。
  • 在同一窗口的新選項卡中而不是在新窗口中打開並創建多個文檔。
  • 將您的工作效率提高 50%,每天為您減少數百次鼠標點擊!
Comments (22)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Good afternoon. I urgently need your help: what VBA code could I use to copy a folder from an Excel workbook and paste it into an existing Excel workbook in another workbook? Would it be possible to copy the formatting just from the formatting?
This comment was minimized by the moderator on the site
Boa tarde. Preciso urgentemente de sua ajuda: qual código de VBA poderia utilizar para copiar a uma planilha inteira de uma pasta de trabalho Excel e colar em várias outras pastas de trabalho Excel já existentes em uma em um mesmo diretório? Teria como copiar apenas a formatação da planilha inteira?
This comment was minimized by the moderator on the site
My scenario is similar, except I have multiple sheets in each file, all with different names but consistent between files. Is there a way to Loop this code to copy the data within the files and paste (values) to specific sheet names in the master workbook? The sheet names in the master are the same as in the files. I want to loop through them. Also, the amount of data in each sheet will vary, so I will need to select the data in each sheet using something like this:

Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select


File sheet names are Giving, Services, Insurance, Car, Other Expenses, etc...

Thanks in advance.
This comment was minimized by the moderator on the site
Hi Andrew Shahan,
The following VBA code can solve your problem. After running the code and selecting a folder, the code will automatically match the worksheet by name and paste the data into the worksheet of the same name in the master workbook.
Sub Merge2MultiSheets()
'Updated by Extendoffice 20221209
    Dim xRg As Range
    Dim xSelItem As Variant
    Dim xFileDlg As FileDialog
    Dim xFileName, xSheetName, xRgStr As String
    Dim xBook As Workbook, xMainBook As Workbook
    Dim xSheet As Worksheet
    On Error Resume Next
    
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    Application.ScreenUpdating = False

    Set xMainBook = ThisWorkbook
    
    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    With xFileDlg
        If .Show = -1 Then
            xSelItem = .SelectedItems.Item(1)
            xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
            If xFileName = "" Then Exit Sub
            
            Do Until xFileName = ""
            Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)

            For Start = 1 To xBook.Worksheets.Count
                Set xSheet = xBook.Worksheets.Item(Start)
                xSheet.Activate
                xSheetName = xSheet.Name
                xSheet.UsedRange.Copy (xMainBook.Worksheets.Item(xSheetName).Range("A1048576").End(xlUp).Offset(1, 0))
            Next
                xFileName = Dir()
                xBook.Close
            Loop
        End If
    End With
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Olá bom dia.
Gostei muito dessde código, mas não me ajudou com os relatórios que eu preciso impreimir.
Preciso imprimir 2.400 relatório de exel que estão em pastas diferentes e não estão configuradas corretamente para impressão. Pode me enviar um códgo de VBA que automatize essas impressões ? Me ajudaria muito, obrigada.
This comment was minimized by the moderator on the site
Hi Maria Soares,
Please check if the VBA code in the following post can help.
How to print multiple workbooks in Excel?
This comment was minimized by the moderator on the site
Hi i want a code to copy the data in 6 different workbooks(in a folder) which has sheets included in them to NEW WORKBOOK. in vba
plz help me asp
This comment was minimized by the moderator on the site
Hi Paranusha,
The VBA script in the following article can combine multiple workbooks or specified sheets of workbooks to a master workbook. Please check if it can help.
How To Combine Multiple Workbooks Into One Master Workbook In Excel?
This comment was minimized by the moderator on the site
for me, the "Sheet1" tab name changes for each of my files. For instance, Tab1, Tab2, Tab3, Tab4...How can I setup a loop to run through a list in excel and keep changing the "Sheet1" name until it runs through everything?
This comment was minimized by the moderator on the site
Hi Nick,The VBA code below can help you solve the problem. Please have a try.<div data-tag="code">Sub LoopThroughFileRename()
'Updated by Extendofice 2021/12/31
Dim xRg As Range
Dim xSelItem As Variant
Dim xFileDlg As FileDialog
Dim xFileName, xSheetName, xRgStr As String
Dim xBook, xWorkBook As Workbook
Dim xSheet As Worksheet
Dim xShs As Sheets
Dim xName As String
Dim xFNum As Integer
On Error Resume Next
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
xFileDlg.Show
xSelItem = xFileDlg.SelectedItems.Item(1)
xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
Do While xFileName <> ""
Set xWorkBook = Workbooks.Open(xSelItem & "\" & xFileName)
Set xShs = xWorkBook.Sheets
For xFNum = 1 To xShs.Count
Set xSheet = xShs.Item(xFNum)
xName = xSheet.Name
xName = Replace(xName, "Sheet", "Tab") 'Replace Sheet with Tab
xSheet.Name = xName
Next
xWorkBook.Save
xWorkBook.Close
xFileName = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
how do you make to code leave a blank if cell is empty?
This comment was minimized by the moderator on the site
Thank you - how would one be able to copy and paste (special values) from each worksheet within a workbook into separate sheets within a main Master file?
This comment was minimized by the moderator on the site
Hi - This code works very well for the first 565 lines for every file, but all lines after are overlapped by the next file.
is there a way to fix this?
This comment was minimized by the moderator on the site
Hi - This code is perfect for what I'm trying to achieve.

Is there a way to loop through all folders and subfolders and perform the copy?


Thanks!
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations