我的数据格式如下
Col1 Col2 Col3 Col4
ServerA 1002 CPU 1
ServerA 1003 Cores 4
ServerA 1005 Memory 16
我需要将数据显示为
Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9
ServerA 1002 CPU 1003 Cores 4 1005 Memory 16
有没有办法使用Excel VBA实现这一目标?
答案 0 :(得分:1)
你可以试试这个:
不是很干净,但我认为它应该符合你的目的。
Option Explicit
Sub Sample()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim RngToUnstack As Range, cel As Range, cel1 As Range
Dim i As Long
Set ws1 = ThisWorkbook.Sheets("Sheet2")
Set ws2 = ThisWorkbook.Sheets("Sheet3")
Set RngToUnstack = ws1.UsedRange
'~~> just an alternative to .UsedRange
'Set RngToUnstack = ws1.Range("A1", "D" & ws1.Range("A" & _
ws1.Rows.Count).End(xlUp).Row)
'~~> construct your unique ID's in Worksheet 2
With ws2
RngToUnstack.Resize(, 1).Copy .Range("A1")
.Range("A1", .Range("A" & .Rows.Count).End(xlUp).Address).RemoveDuplicates 1, xlNo
End With
'~~> loop to populate the ID's
For Each cel1 In ws2.Range("A1", ws2.Range("A" & ws2.Rows.Count).End(xlUp).Address)
i = 0
For Each cel In RngToUnstack.Resize(, 1)
If cel.Value = cel1.Value Then
cel.Resize(, 3).Offset(0, 1).Copy cel1.Offset(0, (3 * i) + 1)
i = i + 1
End If
Next cel
Next cel1
End Sub
<强>结果:强>
假设您的样本数据如下所示:
运行宏后会变成这样: