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?

7
  • Exactly like that? What happens to 1, 4, and Memory ? Commented May 5, 2014 at 4:57
  • @Tim Williams - Apologies. I have updated the post. All the fields need to appear. Commented May 5, 2014 at 5:35
  • And there are varying count of ServerA? I mean it's not always 3 right? There can be 4 ServerA then 5 ServerB for example? Commented May 5, 2014 at 5:43
  • @L42 - That's correct. Commented May 5, 2014 at 6:50
  • Ok so the answer to your question Is there a way to achieve this using Excel VBA? is yes :) Commented May 5, 2014 at 6:56

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.