Power Query course · Lesson 17 of 17

Project: a self-updating monthly sales report

Build a complete monthly sales report: combine a folder of exports, clean them, add product data and targets, check for gaps and refresh with one click.

Advanced 35 min read

This final lesson puts the whole course to work. You will build the kind of workbook that saves a sales analyst a day every month: monthly ERP exports dropped into a folder are combined, cleaned, enriched with product costs, compared with regional targets and summarised in a report that refreshes with one click. Every technique comes from an earlier lesson, and each step links back to it so you can revise as you go.

The brief

  • Source data: the ERP writes one CSV per month, sales_2026-01.csv, sales_2026-02.csv and so on, into a shared folder. Columns: OrderID, OrderDate, Region, Rep, SKU, Qty, UnitPrice, Status.
  • Product master: an Excel table tblProducts in the report workbook with SKU, Product, Category and UnitCost, maintained by purchasing.
  • Targets: an Excel table tblTargets with one row per region and one column per month (Jan to Dec), maintained by the sales director.
  • Output: a summary per month and region with revenue, margin, number of orders, target and percentage of target; plus a clean detail table in the Data Model for PivotTables.
  • Routine: next month, save the new CSV in the folder and click Data › Refresh All. Nothing else.
ABCDEF
1OrderIDOrderDateRegionSKUQtyUnitPrice
2SO-90012026-01-05 northrtr-x2499.00
3SO-90022026-01-05NorthSW-8P 1059.00
4SO-90032026-01-06SOUTHAP-3002145.00
5SO-90042026-01-07SouthRTR-X2199.00

Before: the first rows of sales_2026-01.csv (Rep and Status columns not shown). Inconsistent case and spaces, and everything is text.

Step 1: the settings sheet

Add a sheet Settings with two input cells, as in Parameters and custom functions. Put the folder path in B2 and name the cell pFolder (type the name in the Name Box). Put the report year 2026 in B3 and name it pYear. Then create a blank query (Data › Get Data › From Other Sources › Blank Query), open Home › Advanced Editor, paste the code below and name the query Settings.

Power Query M
let
    Get = (cellName as text) => Excel.CurrentWorkbook(){[Name = cellName]}[Content]{0}[Column1]
in
    [Folder = Get("pFolder"), Year = Get("pYear")]
Settings returns a record; other queries read Settings[Folder] and Settings[Year].

Step 2: the product master

Click inside tblProducts and choose Data › From Table/Range. Name the query Products and make the key clean and unique, because a duplicate SKU would multiply sales rows in the merge (Merge queries: every join kind explained).

Power Query M
let
    Source = Excel.CurrentWorkbook(){[Name = "tblProducts"]}[Content],
    Typed = Table.TransformColumnTypes(Source, {{"SKU", type text}, {"Product", type text}, {"Category", type text}, {"UnitCost", type number}}),
    CleanKey = Table.TransformColumns(Typed, {{"SKU", each Text.Upper(Text.Trim(_)), type text}}),
    UniqueKey = Table.Distinct(CleanKey, {"SKU"})
in
    UniqueKey
Products: typed, keys trimmed and uppercased, duplicates removed.

Step 3: the sales query

Create another blank query named Sales and paste the code. It reads the folder (as in Combine files from a folder, but in a compact hand-written form), cleans the text (Cleaning text and numbers in Power Query), removes cancelled orders (Filtering, sorting and removing rows and columns), adds a month column (Dates, durations and a calendar table), merges product data and calculates revenue and margin (Custom and conditional columns).

Power Query M
let
    Source = Folder.Files(Settings[Folder]),
    CsvOnly = Table.SelectRows(Source, each Text.Lower([Extension]) = ".csv" and Text.StartsWith(Text.Lower([Name]), "sales_")),
    Parsed = Table.AddColumn(CsvOnly, "Data", each Table.PromoteHeaders(
        Csv.Document([Content], [Delimiter = ",", Encoding = 65001, QuoteStyle = QuoteStyle.Csv]),
        [PromoteAllScalars = true])),
    Kept = Table.SelectColumns(Parsed, {"Name", "Data"}),
    Expanded = Table.ExpandTableColumn(Kept, "Data", {"OrderID", "OrderDate", "Region", "Rep", "SKU", "Qty", "UnitPrice", "Status"}),
    Typed = Table.TransformColumnTypes(Expanded, {{"OrderDate", type date}, {"Qty", Int64.Type}, {"UnitPrice", type number}}, "en-US"),
    Cleaned = Table.TransformColumns(Typed, {
        {"Region", each Text.Proper(Text.Trim(_)), type text},
        {"Rep", Text.Trim, type text},
        {"SKU", each Text.Upper(Text.Trim(_)), type text},
        {"Status", Text.Trim, type text}}),
    NotCancelled = Table.SelectRows(Cleaned, each [Status] <> "Cancelled"),
    ThisYear = Table.SelectRows(NotCancelled, each Date.Year([OrderDate]) = Settings[Year]),
    AddMonth = Table.AddColumn(ThisYear, "Month", each Date.StartOfMonth([OrderDate]), type date),
    Merged = Table.NestedJoin(AddMonth, {"SKU"}, Products, {"SKU"}, "P", JoinKind.LeftOuter),
    WithProduct = Table.ExpandTableColumn(Merged, "P", {"Product", "Category", "UnitCost"}),
    AddRevenue = Table.AddColumn(WithProduct, "Revenue", each [Qty] * [UnitPrice], type number),
    AddMargin = Table.AddColumn(AddRevenue, "Margin", each if [UnitCost] = null then null else [Qty] * ([UnitPrice] - [UnitCost]), type number),
    Final = Table.RemoveColumns(AddMargin, {"Name", "Status"})
in
    Final
Sales: one query from folder to enriched detail rows. Step names are short and meaningful, so Applied Steps reads like a checklist.
ABCDEF
1OrderIDMonthRegionSKURevenueMargin
2SO-90012026-01-01NorthRTR-X2396152
3SO-90022026-01-01NorthSW-8P590250
4SO-90032026-01-01SouthAP-300290114
5SO-90042026-01-01SouthRTR-X29938

After: the first four of several hundred January order lines, now clean, typed and enriched (some columns hidden). Unit costs are 61 for RTR-X2, 34 for SW-8P and 88 for AP-300.

Watch out. This query combines three sources: the folder, the Settings cells and the Products table. If refresh stops with a Formula.Firewall error, open Data › Get Data › Data Source Settings, select each source (the folder and the current workbook) and set Edit Permissions › Privacy Level to Organizational for both. See Getting data: files, folders, tables, web pages and databases.

Step 4: a data quality check

A margin of null means an SKU is missing from the product master. Do not let that hide in a total. Create a query Check_UnknownSKUs with a Left Anti join and load it to a small table on the report sheet, where an empty table means all is well.

Power Query M
let
    Anti = Table.NestedJoin(Sales, {"SKU"}, Products, {"SKU"}, "P", JoinKind.LeftAnti),
    SkuList = Table.Distinct(Table.SelectColumns(Anti, {"SKU", "Month"}))
in
    SkuList
Lists each unknown SKU and the month it appeared. Ask purchasing to add it to tblProducts, then refresh.

Step 5: targets from a cross-tab

ABCD
1RegionJanFebMar
2North450004700050000
3South420004400046000

Before: tblTargets, as the sales director likes to type it (April to December not shown).

Unpivot it as in Unpivot and pivot: reshaping tables and turn the month names into real dates, so they match the Month column of Sales:

Power Query M
let
    Source = Excel.CurrentWorkbook(){[Name = "tblTargets"]}[Content],
    Unpivoted = Table.UnpivotOtherColumns(Source, {"Region"}, "MonthName", "Target"),
    AddMonth = Table.AddColumn(Unpivoted, "Month", each
        Date.FromText("1 " & [MonthName] & " " & Text.From(Settings[Year]), [Culture = "en-GB"]), type date),
    Typed = Table.TransformColumnTypes(AddMonth, {{"Region", type text}, {"Target", type number}}),
    Result = Table.SelectColumns(Typed, {"Region", "Month", "Target"})
in
    Result
Targets in long format: one row per region and month.
ABC
1RegionMonthTarget
2North2026-01-0145000
3North2026-02-0147000
4North2026-03-0150000
5South2026-01-0142000
6South2026-02-0144000
7South2026-03-0146000

After: Targets ready to merge on Region and Month.

Step 6: the summary

Group the detail by month and region (Group By: totals, counts and the All Rows trick), then merge the targets on two keys and calculate the percentage. The result below assumes the folder holds the complete January and February exports, several hundred order lines each, so its totals are sums over all those lines rather than over the few sample rows shown earlier.

Power Query M
let
    Grouped = Table.Group(Sales, {"Month", "Region"}, {
        {"Revenue", each List.Sum([Revenue]), type number},
        {"Margin", each List.Sum([Margin]), type number},
        {"Orders", each List.Count(List.Distinct([OrderID])), Int64.Type}}),
    Joined = Table.NestedJoin(Grouped, {"Month", "Region"}, Targets, {"Month", "Region"}, "T", JoinKind.LeftOuter),
    WithTarget = Table.ExpandTableColumn(Joined, "T", {"Target"}),
    AddPct = Table.AddColumn(WithTarget, "% of target", each if [Target] = null or [Target] = 0 then null else [Revenue] / [Target], Percentage.Type),
    Sorted = Table.Sort(AddPct, {{"Month", Order.Ascending}, {"Region", Order.Ascending}})
in
    Sorted
Summary: Orders counts distinct order numbers, because one order can have several lines.
ABCDEF
1MonthRegionRevenueMarginTarget% of target
22026-01-01North482001735045000107.1%
32026-01-01South39650138804200094.4%
42026-02-01North513001847047000109.1%
52026-02-01South441001521044000100.2%

After, with the full January and February files loaded (every order line, not just the four sample rows shown above): the finished summary, Orders column hidden. March appears automatically when sales_2026-03.csv lands in the folder.

Step 7: loading

Decide where each query goes, as discussed in Performance, query folding and refresh options. Right-click each query in Data › Queries & Connections and choose Load To…:

QueryLoad toWhy
SettingsOnly Create ConnectionHelper
ProductsOnly Create Connection (+ Data Model if you want product slicers)Lookup
TargetsOnly Create ConnectionLookup
SalesOnly Create Connection + Add this data to the Data ModelLarge detail for PivotTables
SummaryTable on the Report sheetThe report people read
Check_UnknownSKUsTable on the Report sheetQuality control

Optionally add the calendar query from Dates, durations and a calendar table to the Data Model, relate it to Sales[OrderDate], and build PivotTables and slicers on top (PivotCharts, slicers and timelines). Format the Summary table with a percentage format on % of target and conditional formatting that turns values below 100% red.

Tip. Give the Summary output table a fixed name (Table Design › Table Name, for example tblSummary). Formulas such as XLOOKUP or SUMIFS that point at tblSummary[Revenue] keep working after every refresh, however many rows the table gets.

Step 8: the monthly routine and a test run

  1. Save sales_2026-03.csv into the folder. Do not rename columns or open and re-save it in Excel (Excel may change the date format).
  2. Open the report and choose Data › Refresh All (Ctrl+Alt+F5).
  3. Check Check_UnknownSKUs: it should be empty.
  4. Check the row count in Queries & Connections: Sales should have grown by roughly one month of lines.
  5. Compare the March total in the Summary with the ERP's own total for March. A matching total is the best proof the recipe is right.

To test the robustness before relying on it, try these deliberate accidents on a copy: put a readme.txt in the folder (it is ignored by the extension filter), add an unknown SKU to a CSV (it shows up in the check table), change pYear to 2025 (the report empties because there is no 2025 data), and rename the Qty header in one file (the rows from that file get null quantity and the revenue drops; a good reason to compare totals every month).

Ideas to extend the project

  • Add a Returned status handling: keep returns with negative quantity instead of removing them.
  • Read the targets for several years by adding a Year column to tblTargets and merging on three keys.
  • Replace the local folder path with a SharePoint folder so colleagues can refresh in Excel for the web.
  • Turn the cleaning steps of Sales into a function fnCleanSales and reuse it for a second ERP that exports the same layout.
  • Add a rolling 12-month filter with Date.IsInPreviousNMonths instead of the fixed year.
Note. Everything in this project works in Excel 2016 and later for Windows and in current Microsoft 365 for Mac, except that the folder path must be a Mac path there (/Users/…). In Excel for the web the workbook refreshes only if the folder is a SharePoint or OneDrive folder accessed with From SharePoint Folder.

Check yourself

1. Why are SKU values uppercased and trimmed in both Sales and Products?

2. What does the Check_UnknownSKUs query use?

3. Why count Orders with List.Distinct([OrderID]) instead of Count Rows?

4. Where should the large Sales detail be loaded?

5. A refresh fails with Formula.Firewall. What is the first thing to check?