Let's say I have a table like this:
Country Region Mytext
USA North a
USA South b
Brasil North c
Brasil South d
How can I obtain a pivot like this in Excel?
Country North South
USA a b
Brasil c d
If 'mytext' were a number, I could do a pivot table: since there is only one row per combination of country and region, min = max = sum = avg and any of these aggregate functions would, in fact, show me the result I want.
But what when the field I want is non-numeric? With Python's pandas library, I can use the dataframe.pivot() method even on non-numerical fields, but I haven't found a way to do the same in Excel. I could associate a number to each row, do the pivot in Excel to show that number, and then do a lookup to get the associated text, but it seems a rather convoluted process for something which should really be easier!
you can use the MS Power Query Add-in*. Pivoting tables is without vba right easy. It's free and very effective for data Transformation.
the M-Code
your Output
´* from MS Office 2016, it's fully integrated in Excel as Get & Transform function.
This can be done, but requires VBA to temporarily overwrite a numerical 'placeholder' value in your PivotTable with some text. To enable this, you need to set EnableDataValueEditing = True for the PivotTable. On refresh, you then do a lookup on the numerical placeholder value, and replace it with text. Convoluted, yes. Workaround, yes. But it does the trick. Note that this only 'sticks' until the next time the PivotTable is refreshed, so this code needs to be triggerred on every refresh.
Here's the code I use to do this in one of my own projects. Put this in a Standard Code Module:
And here's the result: a PivotTable with Text in the VALUES area:
Here's the 'conversion' table that tells the code what to display for each number:
I have assigned two named ranges to these, so that my code knows where to find the lookup table:
...and here's how I trigger the Function and pass in the required arguments:
That code goes in the Worksheet Code Module that corresponds to the worksheet where the PivotTable is:
Add the MyText as a row label underneath the Country label, then display the PivotTable in Tabular format under the Pivot Table design tab. Repeat item labels for the country row label field.
For future readers - use two features together:
Ribbon > PivotTable Tools > Report Layout > Show in Tabular Form
and
Ribbon > PivotTable Tools > Report Layout > Repeat all Item Labels
Row fields will be presented left-to-right as vertically repeated text.