The Challenge! - combining revenue files
The task
Section titled “The task”This exercise brings the earlier pages together. Four years of revenue data sit in one folder, in two different layouts:
2015.xlsx,2016.xlsxand2017.xlsxeach have a sheet per month, namedJantoDec. Each sheet is a summary table, with customer category and city down the side, colour, supplier category and supplier name across the top, and grand totals on the last row and column.2018.csvholds the same facts as a list of records, one field per line. Each record is a run of seven lines, fromDatetoRevenue, and the next record starts straight after.
The goal is one table with a row per revenue figure and the columns Date, Color, Supplier Category, Supplier Name, Customer Category, City and Revenue.

The work splits into three parts:
- Combine the 36 monthly sheets from the three workbooks.
- Reshape the CSV.
- Append the two results.
Part 1: the Excel workbooks
Section titled “Part 1: the Excel workbooks”Load the folder
Section titled “Load the folder”- On the Data tab, choose Get Data, then From File, then From Folder, select the folder and choose Transform Data.

- Filter the
Namecolumn to remove2018.csv, because it needs different handling.

- Rename the query
Revenues.
Combine the workbooks
Section titled “Combine the workbooks”Click the Combine Files button in the header of the Content column. In the Combine Files dialog, right-click the top node, Sample File Parameter1, and choose Edit, instead of selecting a single sheet.

Selecting the file node rather than one sheet means each workbook returns its list of sheets, so all twelve months come through instead of one. Power Query also creates the helper queries that every folder combine needs, which apply the same steps to each file in turn.

Back in the Revenues query, keep only the first three columns, which hold the file name, the sheet name and the sheet’s data.

Then tidy the first two columns:
- Remove the
.xlsxextension fromSource.Name, for example with Extract, then Text Before Delimiter on the Transform tab, and rename the columnYear. - Rename
NametoMonth.

Clean each sheet with a function
Section titled “Clean each sheet with a function”Each monthly sheet has an empty first row, a grand total column and a grand total row, and all three have to go before the sheet can be unpivoted. A small function does this for any table passed to it. Create a blank query called fnCleanSummarizedTable, open the Advanced Editor and enter the function. The first line of the block below is the query’s name, not part of the code:
fnCleanSummarizedTable
(inputTable) =>let SkipFirstRow = Table.Skip(inputTable, 1),NoGrandTotalColumn = Table.RemoveColumns(SkipFirstRow, { List.Last(Table.ColumnNames(SkipFirstRow)) } ), Result = Table.RemoveLastN(NoGrandTotalColumn, 1)in ResultThe function does three things, in order:
Table.Skipdrops the first row.Table.RemoveColumnsdrops whichever column is last, which is the grand total.Table.RemoveLastNdrops the last row, which is the grand total row.
In the Revenues query, add a step that applies the function to every sheet:
= Table.AddColumn(#"Renamed Columns", "fnCleanSummarizedTable", each fnCleanSummarizedTable([Data]))
Rename the new column Summarized Table, and remove the Data column.
Unpivot each sheet with the generalised function
Section titled “Unpivot each sheet with the generalised function”The cleaned sheets have two levels of row headings and three levels of column headings, which is the case the generalisable function handles. Create a blank query for it and paste in the code below. This version wraps the function in an outer let, which makes no difference to how it runs, and again the first line is the query’s name:
fnUnpivotSummarizedTable
let Source = (Source, RowFields, ColumnFields, ValueField)=>let #"Filled Down" = Table.FillDown(Source, List.FirstN(Table.ColumnNames(Source), List.Count(RowFields) - 1)), #"Merged Columns" = Table.CombineColumns(#"Filled Down", List.FirstN(Table.ColumnNames(#"Filled Down"), List.Count(RowFields)), Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Merged"), #"Transposed Table" = Table.Transpose(#"Merged Columns"), #"Filled Down1" = Table.FillDown(#"Transposed Table",List.FirstN(Table.ColumnNames(#"Transposed Table"), List.Count(ColumnFields)-1)), #"Promoted Headers" = Table.PromoteHeaders(#"Filled Down1", [PromoteAllScalars=true]), #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Promoted Headers",List.FirstN(Table.ColumnNames(#"Promoted Headers"), List.Count(ColumnFields)) , "Attribute", ValueField), #"Split Column by Delimiter" = Table.SplitColumn(#"Unpivoted Other Columns", "Attribute", Splitter.SplitTextByDelimiter(":", QuoteStyle.Csv), RowFields), #"Renamed Columns" = Table.RenameColumns(#"Split Column by Delimiter", List.Zip({List.FirstN(Table.ColumnNames(#"Split Column by Delimiter"), List.Count(ColumnFields)), ColumnFields})), #"Changed Type" = Table.TransformColumnTypes(#"Renamed Columns",{{ValueField, type number}})in #"Changed Type"in SourceIn Revenues, add a step that calls it on every cleaned sheet, with the row and column headings written straight into the call:
= Table.AddColumn(#"Removed Columns", "Unpivoted", each fnUnpivotSummarizedTable([Summarized Table], {"Customer Category", "City"}, {"Color", "Supplier Category", "Supplier Name"}, "Revenue"))
Remove the Summarized Table column. Then click the expand button on Unpivoted, clear Use original column name as prefix, and click OK. Each month’s rows now appear under the year and month they came from.

That completes the workbooks. The CSV still needs reshaping before the two can be joined.
Part 2: the CSV file
Section titled “Part 2: the CSV file”Load the file
Section titled “Load the file”In the editor, choose New Source, then File, then Text/CSV, select 2018.csv and name the query 2018 Revenues.

Choose Use First Row as Headers, so the columns become Attribute and Value.
Number the lines
Section titled “Number the lines”On the Add Column tab, choose Index Column, then From 0.

Mark where each record starts
Section titled “Mark where each record starts”Every record starts with a Date line. On the Add Column tab, choose Conditional Column and set it up as follows:
- Name the new column
Row ID. - If
AttributeequalsDate, output the value of theIndexcolumn. - Otherwise, output
null.

Each Date line now carries its own line number, and the other lines of the record are empty.

Give every line its record’s ID
Section titled “Give every line its record’s ID”Select Row ID and choose Fill, then Down on the Transform tab. All seven lines of a record now share the same ID, which is what lets them be gathered into one row. Then remove the Index column.

Turn the lines into columns
Section titled “Turn the lines into columns”Select Attribute and choose Pivot Column on the Transform tab. Set Values Column to Value, open Advanced options and choose Don’t Aggregate, because each record has exactly one value for each attribute.

Each record is now one row, identified by its Row ID, with a column for each attribute.

The Row ID has done its job, so remove it.

Part 3: append the two
Section titled “Part 3: append the two”Match the date column
Section titled “Match the date column”The workbook rows have the year and month in separate columns, while the CSV has one Date column holding values such as 2018 Jan. In the Revenues query, select Year and Month, choose Merge Columns on the Transform tab, set the separator to Space and name the new column Date.

Both queries now have the same column names, which is what Append matches on.
Append and finish
Section titled “Append and finish”- In the
Revenuesquery, choose Append Queries on the Home tab and append2018 Revenues. - Set the type of
Dateto Date, which turns2015 Janinto the first day of that month, and the type ofRevenueto Currency. - Choose Close & Load.

All four years now sit in one table with one layout. Because every step works from the folder and from the structure of each file rather than from fixed names, dropping a 2019.xlsx into the folder adds its twelve months on the next refresh.