简体   繁体   中英

Merge excel sheets and workbooks identifying the sheet and workbook source VBA

I have multiple workbooks and worksheets with the same information, I've been trying to merge all this files identifying the information source (Worksheet - workbook).

I've used this code but it just merge the cells and I could not identify the information source (worksheet - Workbook)

Sub merge()
Application.DisplayAlerts = False
For Each hoja In ActiveWorkbook.Sheets
If hoja.Name = "todas" Then hoja.Delete
Next
Sheets.Add before:=Sheets(1)
ActiveSheet.Name = "todas"
For x = 2 To Sheets.Count
Sheets(x).Select
Range("a1:o" & Range("a650000").End(xlUp).Row).Copy
Sheets("todas").Range("a650000").End(xlUp).Offset(1, 0).PasteSpecial 
Paste:=xlValues
Next
Sheets("todas").Select
End Sub     

This is one of the libraries I have to merge:

在此处输入图片说明

I did not have your workbook so I could not test it myself, but the structure is there so you can debug it easily if you ran into an error:

Sub merge()
    Dim rng As Range
    Dim cell As Range
    Application.DisplayAlerts = False
    For Each hoja In ActiveWorkbook.Sheets
    If hoja.Name = "todas" Then hoja.Delete
    Next
    Sheets.Add before:=Sheets(1)
    ActiveSheet.Name = "todas"

    For x = 2 To Sheets.Count
        Set rng = Sheets(x).UsedRange
        rng.Copy

        'Cell in column A after the last row
        Set cell = Sheets("todas").Range("a650000").End(xlUp).Offset(1, 0)
        cell.PasteSpecial Paste:=xlValues

        'Define the range that just got pasted (only column A)
        Set rng = cell.Resize(rng.Rows.Count, 1)

        'Offset it to the column next to the last column
        Set rng = rng.Offset(0, rng.Columns.Count)

        rng.Value = Sheets(x).Name 'paste the name ofthe sheet in each row
        Set rng = rng.Offset(0, 1)
        rng.Value = Sheets(x).Parent.Name 'paste the name of the workbook in each row

    Next
    Sheets("todas").Select
    Application.DisplayAlerts = True
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM