我有一张包含多张纸的xlsx文件,我需要将此文件中的所有纸张合并为一张纸,并在结果中附加纸张名称
sheets :[class A, class B]
class A sheet
id Name
1 a1
2 a2
class B sheet
id Name
1 b1
2 b2
我想要的是合并所有并使用工作表名称作为第3列,因此结果表将是
All sheet:
id Name sheet_name
1 a1 class A
2 a2 class A
1 b1 class B
2 b2 class B
我怎样才能在excel中进行这样的合并?
答案 0 :(得分:2)
你可以试试这段代码:
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