Text FunctionsIntermediate

Split a Product Code Into Colour and Size With TEXTBEFORE and TEXTAFTER

A SKU like TEE-OLIVE-M carries the colour and the size, but neither sits in a column you can filter or total. When every piece is a different length, cutting at the hyphens is the only rule that holds, and TEXTBEFORE and TEXTAFTER cut at hyphens directly.

Task:

You run stock for a small clothing shop, and Black Friday is in two days. The warehouse export in A2:B8 has only a SKU and the units on hand, and every SKU is built the same way: product, colour and size, joined by hyphens. The buyer wants to see the stock by colour and by size before deciding what to push in the sale. In C2, pull out the colour from the SKU in A2, and in D2, pull out the size. Copy both down to row 8. Then, in G3, total the units on hand for the colour named in G2, using the colour column you just built.

Interactive Spreadsheet

Hints

+5 XPno-hints bonus

Solve it on your own to keep the bonus. Each hint gets one step closer to the formula.

The data in this exercise

This is the grid you start with. Cell references in the task — B6, C2 — point at the row numbers and column letters below.

8 rows × 7 columns15 cells you fill in
ABCDEFG
1SKUOn handColourSize
2TEE-OLIVE-M14ColourNAVY
3HOOD-CHARCOAL-XL6Units on hand
4TEE-NAVY-S22
5JKT-RUST-XXL3
6BEANIE-NAVY-OS31
7SWEAT-OATMEAL-L9
8CREWSOCK-OLIVE-XS18
What this exercise teachesMay contain the answer

The pieces of a SKU have no fixed width, so any formula that counts characters is only right for the rows it was written against: RIGHT(A2,2) gives "-M" for a medium and "XL" for an extra large, and "XL" again for XXL. The hyphens are the only thing every row agrees on, and TEXTBEFORE and TEXTAFTER cut at a delimiter rather than at a position. For the size, TEXTAFTER(A2,"-",-1) uses instance -1, which means the last hyphen counting from the right, so it returns M, XL, XXL or OS however long the product and colour are. The colour needs two cuts, so the formula is built inside out: TEXTAFTER(A2,"-") drops the product and leaves OLIVE-M, and TEXTBEFORE of that at "-" drops the size and leaves OLIVE. Doing it in that order means each function only ever looks at the first hyphen of the text it is given, which is the simplest case. Once colour is a column of its own, it behaves like any other data: SUMIF(C2:C8,G2,B2:B8) matches NAVY against the T-shirt's 22 and the beanie's 31 and returns 53. That is the real payoff of splitting a code: a value buried inside a text string cannot be a SUMIF criterion, but a value in its own column can.