Merging workbooks into a new file

Nathalie

I'm trying to merge multiple Excel files from one Folder into a new file. I've found a solution on the Internet, that is adding my files into an open one. I'm not really into VBA Excel, so I think it's a basic problem, but I can't do it, things I've tried haven't worked properly. I would like to change the following code to create a new file called "summary" in the "Path" and copy the Sheets into this new file, overwriting the file every time I do it and deleting the several source files after doing this.

Is there a possibility of merging all those files into one without opening everyone of it?

Sub GetSheets() 
Path = "C:\Merging\"
FileName = Dir(Path & "*.xls")
Do While FileName <> ""
Workbooks.Open FileName:=Path & FileName, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(FileName).Close
FileName = Dir()
Loop
End Sub
PeterT

Your code almost works as is, just needs a couple of slight tweaks. I also agree with @AnalystCave that if this is a repeating exercise, you may consider a more streamlined solution. But this will work for you.

EDIT: changed to deal with existing destination file -- if it exists and is open, then connect to it otherwise open it; then delete all sheets in the existing file to prepare for the copies

Option Explicit

Function IsSheetEmpty(sht As Worksheet) As Boolean
    IsSheetEmpty = Application.WorksheetFunction.CountA(sht.Cells) = 0
End Function

Sub GetSheets()
    Dim Path, Filename As String
    Dim Sheet As Worksheet
    Dim newBook As Workbook
    Dim appSheets As Integer
    Dim srcFile As String
    Dim dstFile As String
    Dim dstPath As String
    Dim wasntAlreadyOpen As Boolean

    Application.ScreenUpdating = False  'go faster by not waiting for display

    '--- create a new workbook with only one worksheet
    dstFile = "AllSheetsHere.xlsx"
    dstPath = ActiveWorkbook.Path & "\" & dstFile
    wasntAlreadyOpen = True
    If Dir(dstPath) = "" Then
        '--- the destination workbook does not (yet) exist, so create it
        appSheets = Application.SheetsInNewWorkbook  'saves the default number of new sheets
        Application.SheetsInNewWorkbook = 1          'force only one new sheet
        Set newBook = Application.Workbooks.Add
        newBook.SaveAs dstFile
        Application.SheetsInNewWorkbook = appSheets  'restores the default number of new sheets
    Else
        '--- the destination workbook exists, so ...
        On Error Resume Next
        wasntAlreadyOpen = False
        Set newBook = Workbooks(dstFile)             'connect if already open
        If newBook Is Nothing Then
            Set newBook = Workbooks.Open(dstPath)    'open if needed
            wasntAlreadyOpen = True
        End If
        On Error GoTo 0
        '--- make sure to delete any/all worksheets so we're only left
        '    with a single empty sheet named "Sheet1"
        Application.DisplayAlerts = False            'we dont need to see the warning message
        Do While newBook.Sheets.Count > 1
            newBook.Sheets(newBook.Sheets.Count).Delete
        Loop
        newBook.Sheets(1).Name = "Sheet1"
        newBook.Sheets(1).Cells.ClearContents
        newBook.Sheets(1).Cells.ClearFormats
        Application.DisplayAlerts = True             'turn alerts back on
    End If

    Path = "C:\Temp\"
    Filename = Dir(Path & "*.xls?")  'add the ? to pick up *.xlsx and *.xlsm files
    Do While Filename <> ""
        srcFile = Path & Filename
        Workbooks.Open Filename:=srcFile, ReadOnly:=True
        For Each Sheet In ActiveWorkbook.Sheets
            '--- potentially check for blank sheets, or only sheets
            '    with specific data on them
            If Not IsSheetEmpty(Sheet) Then
                Sheet.Copy After:=newBook.Sheets(1)
            End If
        Next Sheet
        Workbooks(Filename).Close (False) 'add False to close without saving
        Kill srcFile                      'deletes the file
        Filename = Dir()
    Loop
    '--- delete the original empty worksheet and save the book
    If newBook.Sheets.Count > 1 Then
        newBook.Sheets(1).Delete
    End If
    newBook.Save
    '--- leave it open if it was already open when we started
    If wasntAlreadyOpen Then
        newBook.Close
    End If

    Application.ScreenUpdating = True 're-enable screen updates
End Sub

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Merging text file directories

分類Dev

Merging older versions of a file within Clearcase

分類Dev

Create a new column by merging multiple columns separated by "-" in a dataframe

分類Dev

How to create a new column from merging two or more column?

分類Dev

Merging contents of multiple .csv files into single .csv file

分類Dev

Merging two lines in a text file if they start with the same expression

分類Dev

Merging Multiple Text File Data, but Specific Lines to Another

分類Dev

How to Create an Audio File by Merging Three or More Videos inputs with FFmpeg

分類Dev

Passing strings to new file

分類Dev

Creating new *.reg file

分類Dev

Is there a shortcut for creating a new file?

分類Dev

Copy values between workbooks

分類Dev

Dynamic Ranges in two workbooks

分類Dev

file_put_contents create new file

分類Dev

Write new line at the end of a file

分類Dev

How to add new line in a file

分類Dev

Append a new column to file in perl

分類Dev

add a new line to a delimited file

分類Dev

Adding new columns in a csv file

分類Dev

Creating a .desktop file for a new application

分類Dev

New Terminal bash file error

分類Dev

Workbooks.Add with Workbook in Class

分類Dev

go - Create a new file in a specified path

分類Dev

Generating a new secrets.yml file

分類Dev

Code Blocks(New project/Rename main file)

分類Dev

New generated GeneratedMSBuildEditorConfig file since recent upgrade

分類Dev

Why is LXML Write not pretty printing to a new file?

分類Dev

Trying to create a vimscript function that creates a new file

分類Dev

Avoid overwriting of Image file and Create a new One

Related 関連記事

ホットタグ

アーカイブ