合并每个子文件夹中的所有Excel文件。

huangapple go评论70阅读模式
英文:

Merge all excel files from each sub folder

问题

我需要大家的帮助。
我有一个名为2022的主文件夹,位置在(C:\Users\Username\Desktop\2022),在这个主文件夹中有多个子文件夹,在每个子文件夹中都有多个Excel文件。我需要一个VBA代码来合并每个子文件夹中的所有Excel文件。应该为每个子文件夹创建一个合并文件,每个合并文件应该只包含一个工作表。数据必须仅从每个Excel文件的第1个工作表收集。
到目前为止我的工作:

Sub MergeExcelFiles()

Dim MasterFolder As String, SubFolder As String, FileName As String
Dim MergeFile As Workbook, CurrentFile As Workbook
Dim CurrentSheet As Worksheet, MergeSheet As Worksheet

'Set the path of the master folder
MasterFolder = "C:\Users\Username\Desktop\2022"

'Loop through all subfolders in the master folder
SubFolder = Dir(MasterFolder & "*", vbDirectory)
Do While SubFolder <> ""
If SubFolder <> "." And SubFolder <> ".." Then
'Create a new workbook to store the merged data
Set MergeFile = Workbooks.Add
Set MergeSheet = MergeFile.Sheets(1)

    'Loop through all excel files in the subfolder
    FileName = Dir(MasterFolder & SubFolder & "\*.xlsx*")
    Do While FileName <> ""
        'Open the current file and copy data from sheet 1
        Set CurrentFile = Workbooks.Open(MasterFolder & SubFolder & "\" & FileName)
        Set CurrentSheet = CurrentFile.Sheets(1)
        CurrentSheet.UsedRange.Copy Destination:=MergeSheet.Range("A" & MergeSheet.Cells.SpecialCells(xlCellTypeLastCell).Row)
        CurrentFile.Close SaveChanges:=False
        FileName = Dir()
    Loop

    'Save the merged data to a new file
    MergeFile.SaveAs Filename:=MasterFolder & SubFolder & "\" & SubFolder & "_Merged.xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    MergeFile.Close SaveChanges:=False
End If
SubFolder = Dir()

Loop

MsgBox "Merging completed successfully!"

End Sub

这段代码部分工作正常,首先为第一个子文件夹创建了第一个合并文件,但当它应该进入下一个子文件夹时,Excel应用程序关闭,没有任何错误消息。
任何帮助将不胜感激。

祝好!

英文:

I need your help guys.
I have a master folder named 2022, location (C:\Users\Username\Desktop\2022), in this master folder there are multiple sub folders, in each sub folder there are multiple excel files. I need a VBA code to merge all excel files from each sub folder. A merged file should be created for each sub folder and each merged file should contain only one sheet. Data must be collected only from sheet 1 from each excel file.
My work so far:

Sub MergeExcelFiles()
    
    Dim MasterFolder As String, SubFolder As String, FileName As String
    Dim MergeFile As Workbook, CurrentFile As Workbook
    Dim CurrentSheet As Worksheet, MergeSheet As Worksheet
    
    &#39;Set the path of the master folder
    MasterFolder = &quot;C:\Users\Username\Desktop22\&quot;
    
    &#39;Loop through all subfolders in the master folder
    SubFolder = Dir(MasterFolder &amp; &quot;*&quot;, vbDirectory)
    Do While SubFolder &lt;&gt; &quot;&quot;
        If SubFolder &lt;&gt; &quot;.&quot; And SubFolder &lt;&gt; &quot;..&quot; Then
            &#39;Create a new workbook to store the merged data
            Set MergeFile = Workbooks.Add
            Set MergeSheet = MergeFile.Sheets(1)
            
            &#39;Loop through all excel files in the subfolder
            FileName = Dir(MasterFolder &amp; SubFolder &amp; &quot;\*.xlsx*&quot;)
            Do While FileName &lt;&gt; &quot;&quot;
                &#39;Open the current file and copy data from sheet 1
                Set CurrentFile = Workbooks.Open(MasterFolder &amp; SubFolder &amp; &quot;\&quot; &amp; FileName)
                Set CurrentSheet = CurrentFile.Sheets(1)
                CurrentSheet.UsedRange.Copy Destination:=MergeSheet.Range(&quot;A&quot; &amp; MergeSheet.Cells.SpecialCells(xlCellTypeLastCell).Row)
                CurrentFile.Close SaveChanges:=False
                FileName = Dir()
            Loop
            
            &#39;Save the merged data to a new file
            MergeFile.SaveAs Filename:=MasterFolder &amp; SubFolder &amp; &quot;\&quot; &amp; SubFolder &amp; &quot;_Merged.xlsx&quot;, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
            MergeFile.Close SaveChanges:=False
        End If
        SubFolder = Dir()
    Loop
    
    MsgBox &quot;Merging completed successfully!&quot;
    
End Sub

The code partially works, first merged file for first sub folder is created but when it should go to the next one, the excel application closes without a single error message.
Any help will be greatly appreciated.

Regards

答案1

得分: 1

以下是翻译好的代码部分:

根据FunThomas先生的建议,下面的代码使用了fileSystemObject

Sub test()
Dim MasterFolder As String
Dim fs, subF, subFiles, FL
Dim MergeFile As Workbook, MergeSheet As Worksheet

Application.ScreenUpdating = False

MasterFolder = "C:\Users\UserName\Desktop22\"
Set fs = CreateObject("Scripting.FileSystemObject")

    For Each subF In fs.GetFolder(MasterFolder).SubFolders
        Set subFiles = fs.GetFolder(subF).Files
        Set MergeFile = Workbooks.Add
        Set MergeSheet = MergeFile.Sheets(1)
            For Each FL In subFiles
                Workbooks.Open FL
                With ActiveWorkbook
                    .Sheets("Sheet1").UsedRange.Copy Destination:=MergeSheet.Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
                    .Close SaveChanges:=False
                End With
            Next FL
        With MergeFile
            .SaveAs Filename:=subF & "\" & subF.Name & "_Merged.xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
            .Close SaveChanges:=False
        End With
    Next subF

Application.ScreenUpdating = True
End Sub
英文:

As suggested by Mr. FunThomas, the code below use fileSystemObject

Sub test()
Dim MasterFolder As String
Dim fs, subF, subFiles, FL
Dim MergeFile As Workbook, MergeSheet As Worksheet

Application.ScreenUpdating = False

MasterFolder = &quot;C:\Users\UserName\Desktop22\&quot;
Set fs = CreateObject(&quot;Scripting.FileSystemObject&quot;)

    For Each subF In fs.GetFolder(MasterFolder).SubFolders
        Set subFiles = fs.GetFolder(subF).Files
        Set MergeFile = Workbooks.Add
        Set MergeSheet = MergeFile.Sheets(1)
            For Each FL In subFiles
                Workbooks.Open FL
                With ActiveWorkbook
                    .Sheets(&quot;Sheet1&quot;).UsedRange.Copy Destination:=MergeSheet.Range(&quot;A&quot; &amp; Rows.Count).End(xlUp).Offset(1, 0)
                    .Close SaveChanges:=False
                End With
            Next FL
        With MergeFile
            .SaveAs Filename:=subF &amp; &quot;\&quot; &amp; subF.Name &amp; &quot;_Merged.xlsx&quot;, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
            .Close SaveChanges:=False
        End With
    Next subF

Application.ScreenUpdating = True
End Sub

huangapple
  • 本文由 发表于 2023年5月10日 17:52:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76217035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定