Chapter 5: Data Preparation and Cleaning in Excel

Accounting Analytics: An Integrated Approach

In this chapter

Part II of V: Accounting Analytics with Excel

Chapter 2 of 5 in this Part

  • 5.1 Why Data Preparation Comes First
  • 5.2 Text Functions
  • 5.3 Date Functions
  • 5.4 Conditional Logic
  • Guided Tutorial 5.1
  • 5.6 Lookup Functions
  • Guided Tutorial 5.2
  • 5.8 Missing, Meaningful, and Invalid Values
  • 5.9 Power Query for Repeatable Preparation
  • Guided Tutorial 5.3
  • 5.11 Looking Ahead

Learning objectives

  1. Explain why accounting data must be prepared before it is analyzed, and document the preparation so that a reviewer can repeat it.
  2. Use text and logical functions to extract, standardize, classify, and validate fields, such as the product type encoded in an item code or the payment terms of an invoice.
  3. Use date functions to assign transactions to fiscal periods and to measure the time between business events.

Learning objectives (continued)

  1. Combine data from related tables with XLOOKUP and with INDEX and MATCH, read the VLOOKUP formulas of older workbooks, and recognize when a one-to-many relationship calls for a different approach.
  2. Build a repeatable preparation workflow in Power Query that merges tables, adds calculated columns, and can be refreshed when the source data changes.

The invoice lines do not say when, what or who

  • The Furniture Seasonal Promotion carries the most promotion lines and discount dollars
  • The controller asks how many of those lines fell in the fourth quarter, and how much revenue
  • The lines record what was sold and at what price, but not when it was invoiced
  • Nor the item’s product group, nor the customer: those live in other Tables

5.1 Why Data Preparation Comes First

Preparation turns recorded data into analyzable data

  • Discover, clean, integrate and restructure data for one analysis (Fernandes et al.)
  • The workflow’s third stage: after the question and the data, before the analysis
  • Client data often arrives incomplete and in an unusable form (Lee et al.)
  • Teaching cases rarely cover this step, though practice depends on it (Raschke and Charron)

Every preparation step needs a check

  • A lookup that silently fails, a date in the wrong quarter, a join that duplicates rows
  • None of these errors announces itself
  • So pair each step with a check: unmatched rows counted, totals agreed, forms tested
  • And document each decision, so someone else can repeat it

The destination: one table, every attribute

A diagram of the preparation this chapter performs. Four Tables from the analysis workbook, SalesInvoiceLine, SalesInvoice, Item, and Customer, are connected by their keys: each invoice line carries a SalesInvoiceID and an ItemID, and each invoice carries a CustomerID. Arrows show the columns each Table contributes to a single InvoiceLines table: the line's own quantity, prices, discount, line total, and promotion; the invoice date and customer from SalesInvoice; the item group, item code, and standard cost from Item; and the segment and region from Customer. Columns calculated during preparation, the fiscal year, fiscal quarter, period label, product type, and a whole-quantity check, are shown as added columns.
Figure 5.1 · From Related Tables to One Analytical Table

Each line gains its invoice’s date and customer

Detail of: A diagram of the preparation this chapter performs. Four Tables from the analysis workbook, SalesInvoiceLine, SalesInvoice, Item, and Customer, are connected by their keys: each invoice line carries a SalesInvoiceID and an ItemID, and each invoice carries a CustomerID. Arrows show the columns each Table contributes to a single InvoiceLines table: the line's own quantity, prices, discount, line total, and promotion; the invoice date and customer from SalesInvoice; the item group, item code, and standard cost from Item; and the segment and region from Customer. Columns calculated during preparation, the fiscal year, fiscal quarter, period label, product type, and a whole-quantity check, are shown as added columns.
Figure 5.1 · From Related Tables to One Analytical Table (detail)

Items, customers and new columns complete each row

Detail of: A diagram of the preparation this chapter performs. Four Tables from the analysis workbook, SalesInvoiceLine, SalesInvoice, Item, and Customer, are connected by their keys: each invoice line carries a SalesInvoiceID and an ItemID, and each invoice carries a CustomerID. Arrows show the columns each Table contributes to a single InvoiceLines table: the line's own quantity, prices, discount, line total, and promotion; the invoice date and customer from SalesInvoice; the item group, item code, and standard cost from Item; and the segment and region from Customer. Columns calculated during preparation, the fiscal year, fiscal quarter, period label, product type, and a whole-quantity check, are shown as added columns.
Figure 5.1 · From Related Tables to One Analytical Table (detail)

5.2 Text Functions

Text functions pull attributes out of codes

Table 5.1 · Text functions used for data preparation

Function What it returns Example with a Charles River value
LEFT(text, n) The first n characters LEFT("FUR-DSK-0075",3) returns FUR
MID(text, start, n) n characters starting at a position MID("FUR-DSK-0075",5,3) returns DSK
RIGHT(text, n) The last n characters RIGHT("SI-2025-007947",6) returns 007947
LEN(text) The number of characters LEN("FUR-DSK-0075") returns 12
FIND(find, text) The position of one text inside another FIND("-","FUR-DSK-0075") returns 4

Text functions standardize and convert

Table 5.1 · Text functions used for data preparation

Function What it returns Example with a Charles River value
TRIM(text) The text without leading, trailing, or repeated spaces Removes stray spaces from an imported name
CLEAN(text) The text without the basic non-printing control characters Removes line breaks copied in from another system
SUBSTITUTE(text, old, new) The text with one string replaced by another Replaces “Street” with “St” to standardize addresses
UPPER, LOWER, PROPER The text in capitals, lower case, or with each word capitalized UPPER("Smith Ltd") returns SMITH LTD
EXACT(text1, text2) TRUE if the two texts are identical, including their case EXACT("LLC","Llc") returns FALSE
VALUE(text) The number that a text value represents Converts "007947" to 7947

Test before you clean

  • =LEN([@CustomerName])=LEN(TRIM([@CustomerName])) is TRUE for a name with no stray spaces
  • A COUNTIFS on the result counts the values that fail
  • Charles River’s names, codes and addresses pass: no stray spaces
  • That is a finding to record: the field is free of the problem tested for

Watch out: some text problems are invisible

  • A non-breaking space looks like a space, but TRIM leaves it in place
  • SUBSTITUTE can replace it with an ordinary space before TRIM runs
  • A number stored as text looks like a number, but does not add up or match
  • VALUE converts it to a real number

5.3 Date Functions

Dates assign each transaction to its period

  • YEAR, MONTH and DAY return the parts of a date; EOMONTH returns a month’s last day
  • With a calendar fiscal year, the quarter is ROUNDUP(MONTH([@InvoiceDate])/3,0)
  • One period label, joining year and quarter, groups and sorts better than two numbers
  • A fiscal year that starts in another month needs a shifted formula

Measure time from a fixed as-of date, not TODAY

  • Subtracting dates returns days: due date less invoice date gives the terms
  • DATEDIF returns whole months or years between two dates
  • TODAY changes every day, so an age based on it cannot be reproduced
  • Store the as-of date in a named parameter cell and subtract from that

Watch out: a date stored as text is not a date

  • It sorts alphabetically, fails to match a real date, and misleads in arithmetic
  • It is common in exports that use a different date order
  • DATEVALUE converts one value; Power Query’s data type converts a column
  • Check the type of every date column before you rely on it

5.4 Conditional Logic

Logical functions classify and check

Table 5.2 · Logical functions used for data preparation

Function What it returns Example
IF(test, if_true, if_false) One of two values, depending on a test Label invoices with extended payment terms
IFS(test1, value1, ...) The value paired with the first true test Group payment terms into bands
AND(test1, test2, ...) TRUE only if every test is true Check each part of an item code

Logical functions classify and check (continued)

Table 5.2 · Logical functions used for data preparation

Function What it returns Example
OR(test1, test2, ...) TRUE if at least one test is true Check that terms are one of the standard values
NOT(test) The opposite of the test Flag the lines that are not Furniture
IFERROR(value, if_error) The value, or a substitute if the value is an error Return “No match” when a lookup fails

IFS needs a final TRUE; IFERROR a countable value

  • IFS returns the value of the first true test, so test bands in order
  • End with TRUE to catch every other value; without it, a miss returns #N/A
  • IFERROR hides every error, including a mistyped reference
  • So substitute a value you can count, such as “No match”, never zero or a blank

Check your understanding

Which function does each task?

  1. Take the product type out of an item code
  2. Group invoices into payment-term bands
  3. Age a receivable so the result can be reproduced
  4. Find names with stray spaces

Each task has its function

  1. MID, because the parts of the code have fixed lengths
  2. IFS, ending with TRUE to catch every other value
  3. Subtraction from a named as-of date, never TODAY
  4. LEN compared with LEN of TRIM

Guided Tutorial 5.1: Adding Text, Date, and Logical Columns

Prepare the items and invoices in seven steps

  1. Extract the product type from the item code
  2. Test that every item code has the expected form
  3. Assign each invoice to a fiscal period
  4. Measure the payment terms in days
  5. Group and test the payment terms
  6. Check the period labels
  7. Record the new columns

Every item gains its product type

A mock of the Item Table in the analysis workbook, showing ItemID, ItemCode, ItemName, and ItemGroup for several Furniture items, and two new calculated columns: ProductType, which holds the middle three letters of each item code, such as DSK for a desk and SDB for a sideboard, and CodeCheck, which is TRUE for every row. The formula bar shows =MID([@ItemCode],5,3). The two new columns are outlined.
Figure 5.2 · The Item Table with the Product Type Extracted from the Item Code

Every invoice gains a period and its payment terms

A mock of the SalesInvoice Table in the analysis workbook, showing SalesInvoiceID, InvoiceNumber, InvoiceDate, and DueDate for several invoices dated at the end of the third quarter of 2026 and the start of the fourth, and four new calculated columns: FiscalYear, FiscalQuarter, Period, which joins the two into a label such as 2026-Q3 or 2026-Q4, and DaysToDue, the number of days between the invoice date and the due date. The formula bar shows the formula for Period. The new columns are outlined.
Figure 5.3 · The SalesInvoice Table with Fiscal Period and Payment Terms Columns

Checkpoint

Check that:

  • every item has a three-letter ProductType, and no item code fails the CodeCheck test;
  • every invoice has a Period label from 2024-Q1 to 2026-Q4;
  • every invoice has a TermsGroup label, and no invoice fails the StandardTerms test;
  • the Documentation worksheet lists the new columns.

5.6 Lookup Functions

XLOOKUP follows a key to the matching row

A diagram of an XLOOKUP formula on real Charles River rows. On the left, an invoice line from the SalesInvoiceLine Table shows its SalesInvoiceID. On the right, rows of the SalesInvoice Table show SalesInvoiceID, InvoiceNumber, and InvoiceDate. Arrows show the three arguments of the formula: the lookup value is the line's SalesInvoiceID, the lookup array is the SalesInvoiceID column of SalesInvoice, where the matching row is highlighted, and the return array is the InvoiceDate column, from which the matching row's date is returned to the invoice line. Numbered labels also mark the fourth argument, the value returned when the key is not found.
Figure 5.4 · How XLOOKUP Retrieves a Value from Another Table

XLOOKUP is the better choice for new work

Table 5.4 · Lookup functions compared

Feature VLOOKUP INDEX and MATCH XLOOKUP
Where the key can be Only in the first column of the range In any column In any column
How the return column is chosen By its number in the range By reference to the column By reference to the column
Effect of inserting or deleting columns Can return the wrong column Adjusts, unless a referenced column is deleted Adjusts, unless a referenced column is deleted
Match when the match argument is left out Approximate; FALSE asks for an exact match Approximate; 0 asks for an exact match Exact
When the key is not found, in an exact match #N/A #N/A #N/A, or a value you supply
Availability All versions of Excel All versions of Excel Microsoft 365, Excel 2024, and Excel 2021

Some attributes are two keys away

  • An invoice line carries no order key, but its invoice does
  • One lookup brings the invoice’s SalesOrderID onto the line
  • A second uses it to look up the order date
  • With no shared key at all, build a match key from fields the tables share

Watch out: a lookup returns only the first match

  • Right toward the “one” side: a line to its invoice, an invoice to its customer
  • Wrong toward the “many” side: an order can have several shipments
  • There, summarize instead: MINIFS for the earliest shipment date
  • SUMIFS and COUNTIFS for totals and counts

Check your understanding

Look up or summarize?

  1. Bring the invoice date onto each invoice line
  2. Find an order’s earliest shipment date
  3. Find the date on which each line was ordered
  4. Count the lines on each invoice

Look up toward one; summarize toward many

  1. XLOOKUP: each line has exactly one invoice
  2. MINIFS: an order can have several shipments
  3. Two lookups: line to invoice, then invoice to order
  4. COUNTIFS: an invoice can have many lines

Guided Tutorial 5.2: Bringing Dates and Groups onto the Invoice Lines

Bring the attributes onto the lines in eight steps

  1. Import the sales orders
  2. Bring the invoice date and period onto each line
  3. Follow the key from the invoice to the order
  4. Bring the item group and product type onto each line
  5. Check that every lookup found its match
  6. Reconcile the Furniture revenue by quarter
  7. Find the promotion lines invoiced after the promotion ended
  8. Record the new Table and columns

Promotion lines were invoiced after it ended

A mock of the SalesInvoiceLine Table with the lookup columns added in this tutorial: InvoiceDate, Period, SalesOrderID, OrderDate, ItemGroup, and ProductType, next to the line's ID, promotion, and line total. The rows shown are Furniture lines of the Furniture Seasonal Promotion invoiced after the promotion's end date, each from an order placed while the promotion ran. The InvoiceDate and OrderDate columns are outlined, and the formula bar shows the XLOOKUP formula for InvoiceDate.
Figure 5.5 · Invoice Lines with Their Looked-Up Dates and Groups

Checkpoint

Check that:

  • the SalesInvoiceLine Table has six new lookup columns, and none of them contains “No match”;
  • the Furniture revenue for 2026-Q3 and 2026-Q4 agrees with the Part I case;
  • you have counted the promotion 8 lines invoiced after the promotion’s end date;
  • the Documentation worksheet lists the SalesOrder Table and the six new columns.

5.8 Missing, Meaningful, and Invalid Values

A blank is not always missing

  • A blank PromotionID means the line carried no promotion
  • A blank ShipmentLineID on a design service means nothing was shipped
  • A blank TrackingNumber is different: the information should exist
  • Decide which kind a blank is, then record the decision

A value can be present and still invalid

  • Items sold by the unit should have whole quantities
  • Most of their invoice lines carry fractional quantities
  • Ask the source system’s owners, and check whether it changes the answer
  • Revenue, list amounts and discounts are consistent, so record a limitation

Check your understanding

Missing, meaningful or invalid?

  1. A blank PromotionID on an invoice line
  2. A blank TrackingNumber on a shipment
  3. A fractional quantity for an item sold by the unit
  4. A lookup that returns “No match”

Decide what a value means before you fix it

  1. Meaningful: the line had no promotion, so leave it blank
  2. Missing: the shipment should have one, so report it
  3. Present but invalid: a validity finding to record
  4. A failed match: find out why the key has no row

5.9 Power Query for Repeatable Preparation

A merge is Power Query’s lookup

  • Lookup columns recalculate on every refresh and spread the logic across columns
  • Merge Queries matches a key column and adds the second query’s rows
  • Expand only the columns you need, without the name prefix
  • The whole preparation becomes one recorded procedure

The join kind decides which rows a merge keeps

Table 5.5 · Join kinds in Power Query merges

Join kind Rows in the result Accounting use
Left outer Every row of the first query, with the matching rows of the second Adding invoice and item details to every invoice line
Inner Only the rows that match in both queries Keeping only lines whose item appears in a filtered item list
Full outer Every row of both queries, matched where possible Comparing two lists, such as a sub-ledger and a ledger extract
Left anti Only the rows of the first query that have no match in the second Finding orphaned records, such as lines whose item is missing

Custom columns calculate inside the query

  • Written in M: Date.Year([InvoiceDate]), Date.QuarterOfYear([InvoiceDate])
  • Text.Middle counts from zero, so the product type starts at 4, not 5
  • Conditional Column builds an if, then, else through a dialog
  • Reference starts a new query from another, which stays unchanged

Guided Tutorial 5.3: Building InvoiceLines in Power Query

Build InvoiceLines in seven steps

  1. Open the Power Query Editor and import the customers
  2. Start the InvoiceLines query from the invoice lines
  3. Merge in the invoice details
  4. Merge in the item and customer details
  5. Add the calculated columns
  6. Load InvoiceLines and check the result
  7. Record the query and refresh

Merge on the key, with a left outer join

A mock of the Power Query Merge dialog. The upper table is the InvoiceLines query with its SalesInvoiceID column selected, and the lower table is the SalesInvoice query with its SalesInvoiceID column selected, both showing their first rows. The Join Kind is Left Outer, and a message at the bottom estimates that the selection matches every row from the first table. The two key columns and the join kind are outlined.
Figure 5.6 · The Merge Dialog in Power Query

Five custom columns finish InvoiceLines

Table 5.6 · Custom columns for the InvoiceLines query

New column name Custom column formula
FiscalYear Date.Year([InvoiceDate])
FiscalQuarter Date.QuarterOfYear([InvoiceDate])
Period Text.From([FiscalYear]) & "-Q" & Text.From([FiscalQuarter])
ProductType Text.Middle([ItemCode], 4, 3)
WholeQuantity [Quantity] = Number.RoundDown([Quantity])

InvoiceLines agrees with the lines it came from

A mock of the InvoiceLines worksheet. Seven of the Table's columns are shown: SalesInvoiceLineID, Quantity, InvoiceDate, ItemGroup, CustomerSegment, Period, and WholeQuantity; the Table also holds the line's other columns and the other merged and calculated columns. The Queries and Connections pane at the right lists every query with the number of rows it loaded, and InvoiceLines has as many rows as SalesInvoiceLine. The InvoiceLines entry in the pane is outlined.
Figure 5.8 · The InvoiceLines Table Loaded by Power Query

Checkpoint

Check that:

  • InvoiceLines has exactly as many rows as SalesInvoiceLine, and the same line total;
  • its Furniture revenue for each quarter of 2026 agrees with the lookups from Tutorial 5.2;
  • most lines are flagged as having a fractional quantity, and the Documentation worksheet records it;
  • a refresh rebuilds InvoiceLines without any change to the totals.

5.11 Looking Ahead

Back to the controller’s question

  • The Furniture Seasonal Promotion priced orders placed in September and October
  • Many were invoiced after it ended, so its effect reaches further into the fourth quarter
  • InvoiceLines now carries the period, the product group and type, and the customer segment
  • Chapter 6 summarizes it to explain the change in the Furniture margin

Summary

  • Preparation brings the attributes together, with a check at every step
  • Text, date and logical functions extract, assign and classify values
  • Lookups follow keys toward the one side; summaries handle the many side
  • Blanks can be meaningful, and present values can still be invalid
  • Power Query repeats the preparation as one recorded, refreshable query

Key terms

As-of date · Custom column · Data preparation · Fiscal period · INDEX and MATCH · Join kind · Left outer join · Logical function · Lookup function · Match key · Meaningful blank · Merge · Reference query · Text function · Validity check · XLOOKUP

Practice and next steps

  • Financial Accounting
    • Exercise 5.1: Net Furniture Revenue by Quarter
    • Exercise 5.2: Testing Document Numbers Against Dates
  • Managerial Accounting
    • Exercise 5.3: The Furniture Product Mix
    • Exercise 5.4: How Long Orders Take to Be Invoiced
  • Auditing
    • Exercise 5.5: Testing for Related-Party Suppliers
    • Exercise 5.6: Reviewing the Supplier and Item Master Files

Next: Chapter 6: Descriptive and Diagnostic Analytics in Excel

About these slides

These slides accompany Accounting Analytics: An Integrated Approach, licensed under CC BY-SA 4.0. Every figure and table comes from the chapter:

https://aa.accountinganalyticshub.com/chapters/05-data-preparation/chapter.html