0

I have data in the following format

Col1     Col2    Col3    Col4
ServerA  1002    CPU     1
ServerA  1003    Cores   4
ServerA  1005    Memory  16

I need the data to appear as

Col1     Col2     Col3     Col4     Col5     Col6    Col7   Col8     Col9
ServerA  1002     CPU      1003     Cores    4       1005   Memory   16

Is there a way to achieve this using Excel VBA?

Community
  • 1
  • 1
PeanutsMonkey
  • 6,919
  • 23
  • 73
  • 103

1 Answers1

1

You can try this:
Not very clean but I think it should serve your purpose.

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

Result:

Suppose your sample data looks like this:
enter image description here

After running the macro will become like this:
enter image description here

L42
  • 19,427
  • 11
  • 44
  • 68