archive

Excel: How to “Unpivot” a Table

How to convert this:

to this:

Great VisualBasic script for Excel which does exactly that:

Option Explicit
Sub MoveData()
Dim LC As Long, LRO As Long, NR As Long, HowMany As Long, a As Long, b As Long
Dim c As Range, rng As Range
Application.ScreenUpdating = False
LRO = Sheets("Output").Cells(Rows.Count, 1).End(xlUp).Row
If LRO > 1 Then Sheets("Output").Range("A2:E" & LRO).ClearContents
NR = 2
With Sheets("Input")
LC = .Cells(1, Columns.Count).End(xlToLeft).Column
For Each c In .Range("A2", .Range("A" & Rows.Count).End(xlUp))
Set rng = .Range(.Cells(c.Row, 3), .Cells(c.Row, LC))
HowMany = Application.WorksheetFunction.CountIf(rng, ">-10000")
If HowMany > 0 Then
.Range("A" & c.Row & ":C" & c.Row).Copy Sheets("Output").Range("A" & NR & ":A" & NR + HowMany - 1)
b = NR
For a = 4 To LC Step 1
If .Cells(c.Row, a).Value > -10000 Then
Sheets("Output").Range("D" & b) = .Cells(1, a)
Sheets("Output").Range("E" & b) = .Cells(c.Row, a)
b = b + 1
End If
Next a
NR = NR + HowMany
End If
Next c
End With
Sheets("Output").Select
Application.ScreenUpdating = True
End Sub

Source

Comments are closed.