Skip to content

Instantly share code, notes, and snippets.

@Medohh2120
Last active January 26, 2026 03:49
Show Gist options
  • Select an option

  • Save Medohh2120/f8553c149684e39bb499249e39f01017 to your computer and use it in GitHub Desktop.

Select an option

Save Medohh2120/f8553c149684e39bb499249e39f01017 to your computer and use it in GitHub Desktop.
Unpivot 2 Headers table
/*
Name: UNPIVOT_PLUS
Description: Given a Table or a range with headers, unpivots all columns (all or nothing)
optionally support 2 headers.
optionally removing Grid blank entries.
optionally removing Grid errors.
Made By: Medohh2120
*/
UNPIVOT_PLUS=LAMBDA(Table, [Hdr_name], [Has2Hdrs], [TopHdr_name], [value_name], [Remove_blanks], [Remove_errors],
LET(
/* 1. Preliminary Setup */
TL_Cell, IF(INDEX(Table, 1, 1) = "", "Attribute2", INDEX(Table, 1, 1)),
Has2Hdrs, IF(ISOMITTED(Has2Hdrs), FALSE, Has2Hdrs),
/* 2. Optional Arguments */
Hdr_name, IF(ISOMITTED(Hdr_name), "Attribute1", Hdr_name),
TopHdr_name, IF(ISOMITTED(TopHdr_name), IF(TL_Cell = "", "Attribute2", TL_Cell), TopHdr_name),
value_name, IF(ISOMITTED(value_name), "Value", value_name),
Remove_blanks, IF(ISOMITTED(Remove_blanks), TRUE, Remove_blanks),
Remove_errors, IF(ISOMITTED(Remove_errors), TRUE, Remove_errors),
/* 3. Extract Data */
Grid, IF(Has2Hdrs, DROP(Table, 2, 1), DROP(Table, 1, 1)),
col, IF(Has2Hdrs, DROP(TAKE(Table, , 1), 2), DROP(TAKE(Table, , 1), 1)),
Tophdr, DROP(TAKE(Table, 1), , 1),
Hdr, IF(Has2Hdrs, TAKE(DROP(Table, 1, 1), 1), TAKE(DROP(Table, , 1), 1)),
/* 4. Flatten & broadcast */
r, ROW(Grid),
c, COLUMN(Grid),
f_Grid,TOCOL(GRID),
f_Col, TOCOL( IF(c, col) ),
f_Hdr, TOCOL( IF(r, Hdr) ),
/* 5. Stack Everything */
stacked, IF(Has2Hdrs,
LET(
f_TopHdr, TOCOL(IF(r, Tophdr)),
ColHdr, INDEX(Table, 2, 1),
VSTACK(
HSTACK(ColHdr, Hdr_name, TopHdr_name, value_name),
HSTACK(f_Col, f_Hdr, f_TopHdr, f_Grid)
)
),
VSTACK(
HSTACK(TL_Cell, Hdr_name, value_name),
HSTACK(f_Col, f_Hdr, f_Grid)
)
),
/* 6. handle all four states (Blanks, Errors, Both, None) */
FILTER(stacked,
VSTACK(1, // 1 forces header retention
NOT(
(Remove_blanks * ISBLANK(f_Grid))
+
(Remove_errors * ISERROR(f_Grid))
)
)
)
)
);
@Medohh2120
Copy link
Author

Warning: Data range Must be updated according to given number of headers:

2 Headers in action:

image image

1 Header in action (defaults to 1 header):

image image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment