【问题标题】:Merge excel sheets and workbooks identifying the sheet and workbook source VBA合并识别工作表和工作簿源 VBA 的 excel 工作表和工作簿
【发布时间】:2018-01-04 23:06:57
【问题描述】:

我有多个具有相同信息的工作簿和工作表,我一直在尝试合并所有这些文件以识别信息源(工作表 - 工作簿)。

我使用过这段代码,但它只是合并单元格,我无法识别信息源(工作表 - 工作簿)

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     

这是我必须合并的库之一:

【问题讨论】:

  • Sheets(x).PARENT.Name

标签: vba excel merge identity


【解决方案1】:

我没有你的工作簿,所以我无法自己测试它,但结构已经存在,因此如果遇到错误,你可以轻松调试它:

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

【讨论】:

  • 感谢您的帮助,这有助于我识别工作簿和工作表,但您知道如何添加代码以合并不同的工作簿吗?
  • 要合并所有打开的工作簿,还是文件夹中的工作簿?
  • 您只需要使用 DIR 函数遍历文件夹中的文件,然后使用我编写的代码将它们堆叠在一张纸上。实际上,将代码编写在一个独立的工作簿中,并将excel文件复制到同一文件夹中并从工作簿中运行代码,它应该一个接一个地打开excel文件,收集每个工作表和每个excel文件中的数据。开始做一些事情,如果你遇到问题,你总是可以在这里得到帮助。查找 DIR 函数示例以了解如何构建您的主子
猜你喜欢
  • 1970-01-01
  • 2016-10-25
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
相关资源
最近更新 更多