how can i merge all worksheets into single worksheet in excel
本问题已经有最佳答案,请猛点这里访问。
我有一个包含多张工作表的 xlsx 文件,我需要将此文件中的所有工作表合并为一张工作表,并将工作表名称附加到结果中
1 2 3 4 5 6 7 8 9 10 | sheets :[class A, class B] class A sheet id Name 1 a1 2 a2 class B sheet id Name 1 b1 2 b2 |
我想要的是合并所有并将工作表名称用作第三列,因此结果表将是
1 2 3 4 5 6 | All sheet: id Name sheet_name 1 a1 class A 2 a2 class A 1 b1 class B 2 b2 class B |
如何在 excel 中进行这样的合并?
你可以试试这个代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | Sub main() Dim isht As Long Dim allSht As Worksheet Dim dataArr As Variant Dim shtName As String Set allSht = Worksheets.Add(After:=Worksheets(Worksheets.Count)) For isht = 1 To Worksheets.Count - 1 With Worksheets(isht) dataArr = Intersect(.UsedRange, .Range("A:B")).Value shtName = .Name End With With allSht With .Cells(.Rows.Count, 1).End(xlUp).Offset(1) .Resize(UBound(dataArr, 1), UBound(dataArr, 2)).Value = dataArr .Offset(, 2) ="sheet_name" .Offset(1, 2).Resize(UBound(dataArr, 1) - 1).Value = shtName End With End With Next isht With allSht .Rows(1).Delete .Name ="All" End With End Sub |