How to unstack data automatically using VBA. Many a times we receive data from certain databases or accounting software arranged one below the other. Such data with multiple items arranged in a stack is not easy to analyze. We need to unstack the data for a better and quicker analysis. The video below describes how to unstack such data manually and automatically:
Here’s the complete VBA code:
Option Explicit
Sub prefillData()
Dim i As Long, j As Long, k As Long
i = 2
j = 4
k = 2
Do While Cells(i, 1) <> “”
Cells(i, j) = “abcA” & k
j = j + 1
k = k + 1
If k = 5 Then
j = 4
i = 3
Cells(i, j) = “abcA” & k
k = k + 1
j = j + 1
ElseIf k > 7 Then Exit Sub
End If
Loop
End Sub
Option Explicit
Sub unstackData()
Dim lastrow As Long
lastrow = Sheets(“Sheet1”).Range(“A” & Rows.count).End(xlUp).Row
‘Range(“D2”) = “abcA2”
‘Range(“E2”) = “abcA3”
‘Range(“F2”) = “abcA4”
‘Range(“D3”) = “abcA5”
‘Range(“E3”) = “abcA6”
‘Range(“F3”) = “abcA7”
prefillData
lastrow = lastrow / 3
Range(“D2:F3”).AutoFill Destination:=Range(“D2:F” & (lastrow + 1)), Type:=xlFillDefault
Range(“D2:F” & (lastrow + 1)).Replace what:=”abc”, replacement:=”=”
Range(“G1”).Select
End Sub
The recorded macro:
Option Explicit
Sub Macro1()
‘
‘ Macro1 Macro
‘
‘
Range(“D2”).Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = “=RC[-3]”
Range(“E2”).Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = “=R[1]C[-4]”
Range(“F2”).Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = “=R[2]C[-5]”
Range(“D2”).Select
ActiveCell.FormulaR1C1 = “abcA2”
Range(“E2”).Select
ActiveCell.FormulaR1C1 = “abcA3”
Range(“F2”).Select
ActiveCell.FormulaR1C1 = “abcA4”
Range(“D3”).Select
ActiveCell.FormulaR1C1 = “abcA5”
Range(“E3”).Select
ActiveCell.FormulaR1C1 = “abcA6”
Range(“F3”).Select
ActiveCell.FormulaR1C1 = “abcA7”
Range(“D2:F3”).Select
ActiveWindow.SmallScroll Down:=-12
Application.CellDragAndDrop = True
Selection.AutoFill Destination:=Range(“D2:F43”), Type:=xlFillDefault
Range(“D2:F43″).Select
Selection.Replace what:=”abc”, replacement:=”=”, lookat:=xlPart, _
searchorder:=xlByRows, MatchCase:=False, searchformat:=False, _
ReplaceFormat:=False, formulaversion:=xlReplaceFormula2
Selection.NumberFormat = “#,##0;-#,##0;”
Range(“F16”).Select
ActiveWindow.SmallScroll Down:=-12
End Sub
Here’s a sample file for download and practice: