这是一个 VBA 解决方案,它将转换后的表格放在新工作表上:
Sub tgr()
Dim wsData As Worksheet
Dim wsDest As Worksheet
Dim NameCell As Range
Dim rngFound As Range
Dim arrData() As Variant
Dim strFirst As String
Dim DataIndex As Long
Dim cIndex As Long
Set wsData = ActiveSheet
Set wsDest = Sheets.Add(After:=Sheets(Sheets.Count))
wsData.Range("A1", wsData.Cells(Rows.Count, "A").End(xlUp)).AdvancedFilter xlFilterCopy, , wsDest.Range("A1"), True
wsData.Range("B1", wsData.Cells(Rows.Count, "B").End(xlUp)).AdvancedFilter xlFilterCopy, , wsDest.Range("B1"), True
wsDest.Range("B2", wsDest.Cells(Rows.Count, "B").End(xlUp)).Copy
wsDest.Range("B1").PasteSpecial xlPasteValues, Transpose:=True
With wsDest.Range("A1", wsDest.Cells(1, Columns.Count).End(xlToLeft))
.Font.Bold = True
.Borders(xlEdgeBottom).LineStyle = xlContinuous
With .Offset(, 1).Resize(, .Columns.Count - 1)
.Value = Application.Transpose(Evaluate("Index(""Group""&Row(1:" & .Columns.Count & "),)"))
End With
End With
ReDim arrData(1 To wsDest.Cells(Rows.Count, "A").End(xlUp).Row - 1, 1 To wsDest.Cells(1, Columns.Count).End(xlToLeft).Column - 1)
For Each NameCell In wsDest.Range("A2", wsDest.Cells(Rows.Count, "A").End(xlUp)).Cells
DataIndex = DataIndex + 1
Set rngFound = wsData.Columns("A").Find(NameCell.Text, , xlValues, xlWhole)
If Not rngFound Is Nothing Then
cIndex = 0
strFirst = rngFound.Address
Do
cIndex = cIndex + 1
arrData(DataIndex, cIndex) = wsData.Cells(rngFound.Row, "B").Text
Set rngFound = wsData.Columns("A").Find(NameCell.Text, rngFound, xlValues, xlWhole)
Loop While rngFound.Address <> strFirst
End If
Next NameCell
If DataIndex > 0 Then wsDest.Range("B2").Resize(UBound(arrData, 1), UBound(arrData, 2)).Value = arrData
Set wsData = Nothing
Set wsDest = Nothing
Set NameCell = Nothing
Set rngFound = Nothing
Erase arrData
End Sub
如何使用宏:
- 制作宏将在其上运行的工作簿的副本
- 始终在工作簿副本上运行新代码,以防代码运行不顺畅
- 对于删除任何内容的任何代码来说尤其如此
- 在复制的工作簿中,按 ALT+F11 打开 Visual Basic 编辑器
- 插入 | 模块复制提供的代码并粘贴到模块中
- 关闭 Visual Basic 编辑器
- 在 Excel 中,按 ALT+F8 以调出要运行的可用宏列表
- 双击所需的宏(我将这个命名为 tgr)