• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Parent-Child hierarchies in excel vba code

Ganesh Babi

New Member
Parent NameChild NameAmtOutputSum of AmtPlease help me to sort out the query
Ax12A
24​
By24x
17​
Cz3z
7​
Ax5B
51​
Az2x
23​
By4y
28​
Az5C
16​
Bx23x
7​
Cy6y
6​
Cx7z
3​
 
Please assist me in sorting the below excel query and the expected output is showing in the below table.
Parent NameChild NameAmtOutputSum of Amt
Ax12A24
By24x17
Cz3z7
Ax5B51
Az2x23
By4y28
Az5C16
Bx23x7
Cy6y6
Cx7z3
 
Agreed, we can use PivotTables for this. We are planning to automate the process, which is why we need VBA code. However, we can't use too many PivotTables in the Excel sheet.
 
Code:
x = [LET(a,DROP(PIVOTBY(Table1[[Parent Name]:[Child Name]],,Table1[Amt],SUM,0,-2),1),HSTACK(IF(CHOOSECOLS(a,2)="",CHOOSECOLS(a,1),CHOOSECOLS(a,2)),CHOOSECOLS(a,3)))]
Range("T2").Resize(UBound(x), UBound(x, 2)).Value = x
Table1 is the name of my source data table; adjust the code to match your table's name.

or
Code:
With Range("I2")
  .Formula2R1C1 = "=LET(a,DROP(PIVOTBY(Table1a[[Parent Name]:[Child Name]],,Table1a[Amt],SUM,0,-2),1),HSTACK(IF(CHOOSECOLS(a,2)="""",CHOOSECOLS(a,1),CHOOSECOLS(a,2)),CHOOSECOLS(a,3)))"
  .SpillingToRange.Value = .SpillingToRange.Value
End With
 
Last edited:
Back
Top