How to Make Customer Account Statements in Google Sheets: One PDF per Customer with Aging (2026)

An invoice asks for one payment. A statement of account shows a customer the whole picture: what they owed at the start of the month, every invoice, payment and credit since, the balance after each one, and how much of what is still open is current or 30, 60 or 90 days late. Customers who get several invoices a month, pay in lumps or lose invoices in their inbox pay faster from one statement than from ten reminders, and a statement is the easiest way to settle “we think we paid that” before it turns into an argument. If your invoices live in a Google Sheet, you already have everything a statement needs. This guide sets up a ledger tab with one row per invoice or payment, formulas for each customer's balance and aging, a printable one-customer statement built with FILTER and SCAN, and a free Apps Script that makes a PDF statement for every customer at once (and can email them) at the end of each month, with a preview mode so you can check them first.

Two kinds of statement, one sheet. An activity (balance-forward) statement lists everything that happened in the period, from the opening balance to the closing balance. An open-item statement lists only the invoices that are still unpaid, with their age. The script puts both on the same page: the activity table first, then the aging summary and the open invoices.

Step 1: a Ledger tab with one row per invoice, payment or credit

Name the tab Ledger. Every document that changes what a customer owes gets a row: invoices, extra charges, payments received, credit notes and write-offs. Never edit a row to “net” a payment into an invoice; add a Payment row instead, so the history stays intact. The script finds columns by their header, so the order is up to you, but the formulas below assume this layout:

ColHeaderWhat goes in it
ADateThe invoice date, or the day the payment arrived
BCustomerExactly the same name every time (the script ignores capitals and extra spaces, the formulas ignore capitals). A dropdown from the Customers tab (Data › Data validation) keeps it consistent.
CTypeInvoice, Charge, Fee or Debit raise the balance; Payment, Credit, Credit note or Write-off lower it. Use a dropdown so nothing else sneaks in.
DReferenceInvoice number, payment reference or credit note number (optional, but you need invoice numbers for column G)
EAmountAlways a positive number; the Type decides whether it adds or subtracts
FDue dateFor invoices and charges. If you leave it empty, the script uses the date plus TERMS_DAYS (30); the formulas need it filled, so type it or use =A2+30.
GApplies toOptional, on payments and credits: the invoice number they pay. Leave it empty for a lump-sum payment; it then pays the oldest invoices first.

Format A and F as dates and E as currency. One currency per sheet: if you bill in two currencies, keep two ledgers.

Step 2: balance and aging per customer with formulas

Add two helper columns to the Ledger. In H1 type Signed and in H2 put one formula for the whole column; it turns every amount into a plus or minus:

=ARRAYFORMULA(IF(E2:E="", "", IF(REGEXMATCH(LOWER(C2:C), "^(invoice|charge|fee|debit)$"), E2:E, -E2:E)))

In I1 type Open and in I2 put this, then fill it down. For an invoice it shows what is still unpaid after the payments whose Applies to names that invoice:

=IF(N(H2)<=0, "", IF(D2="", E2, MAX(0, E2 - SUMIFS(E:E, B:B, B2, G:G, D2))))

Now a Customers tab: Customer in A, Email in B (several addresses separated by commas are fine), Address in C (press Ctrl+Enter, or ⌘+Enter on a Mac, for a new line inside the cell; the script prints each line), then Balance, Current, 1-30, 31-60, 61-90 and Over 90 in D to I. Put the “as of” date in L1; =EOMONTH(TODAY(), -1) gives the last day of last month, the same date the script uses by default. Then in row 2, filled down:

D2  =SUMIFS(Ledger!H:H, Ledger!B:B, $A2, Ledger!A:A, "<="&$L$1)
E2  =SUMIFS(Ledger!I:I, Ledger!B:B, $A2, Ledger!A:A, "<="&$L$1, Ledger!F:F, ">="&$L$1)
F2  =SUMIFS(Ledger!I:I, Ledger!B:B, $A2, Ledger!A:A, "<="&$L$1, Ledger!F:F, "<"&$L$1, Ledger!F:F, ">="&$L$1-30)
G2  =SUMIFS(Ledger!I:I, Ledger!B:B, $A2, Ledger!A:A, "<="&$L$1, Ledger!F:F, "<"&$L$1-30, Ledger!F:F, ">="&$L$1-60)
H2  =SUMIFS(Ledger!I:I, Ledger!B:B, $A2, Ledger!A:A, "<="&$L$1, Ledger!F:F, "<"&$L$1-60, Ledger!F:F, ">="&$L$1-90)
I2  =SUMIFS(Ledger!I:I, Ledger!B:B, $A2, Ledger!A:A, "<="&$L$1, Ledger!F:F, "<"&$L$1-90)

An invoice due on the as-of date or later is current; 1 to 30 days past its due date lands in 1-30, and so on. Sort or filter the tab by Over 90 and you have your collection list. Two limits of the formula version: the Open column only knows about payments that name their invoice in Applies to (a lump-sum payment lowers the Balance but not the aging columns, so the aging adds up to more than the Balance), and it counts payments made after the as-of date. The script below handles both.

Step 3, quick version: one customer's statement on a tab you can print

For the occasional “can you send me a statement?”, a Statement tab is enough. In A1:A5 type the labels Customer, From, To, Opening balance and Closing balance. Make B1 a dropdown of your customers (Data › Data validation › Dropdown (from a range), range Customers!A2:A) and type the period dates in B2 and B3. Then:

B4  =SUMIFS(Ledger!H:H, Ledger!B:B, B1, Ledger!A:A, "<"&B2)
B5  =B4 + SUM(D7:D)
A6:E6  Date | Type | Reference | Amount | Balance
A7  =IFERROR(SORT(FILTER({Ledger!A2:A, Ledger!C2:C, Ledger!D2:D, Ledger!H2:H}, Ledger!B2:B=B1, Ledger!A2:A>=B2, Ledger!A2:A<=B3), 1, TRUE), "No activity")
E7  =ARRAYFORMULA(IF(D7:D="", "", SCAN(B4, D7:D, LAMBDA(balance, amount, balance + N(amount)))))

FILTER pulls the customer's rows for the period, and SCAN walks down the Amount column carrying the balance along, which gives the running balance on every line (see Google's SCAN function help, whose first example is exactly a running total). Charges show as positive amounts and payments as negative ones. Pick another customer in B1 and the whole tab rebuilds. To print it, select A1:E and use File › Print with Selected cells, or download it as a PDF from the same dialog.

This is one customer at a time, without aging or a list of open invoices, and rows on the same day may not stay in sheet order after SORT. When you want every customer's statement at month end, use the script.

Step 4: the script (a PDF statement for every customer)

Create a Drive folder for the statements and copy its ID (the part of its URL after /folders/). In the sheet, open Extensions › Apps Script, paste the script, put in the folder ID, your business name and the lines to print under it (address, email, how to pay), and save. Reload the sheet, then use Statements › Make customer statements and approve the permissions the first time. With the default settings it makes three statements named “PREVIEW Statement - …” for last month and sends nothing, so you can open the PDFs and check the numbers against your ledger.

// Customer account statements from a Google Sheets ledger: one PDF per customer with the
// opening balance, every invoice and payment in the period with a running balance, aging
// (current, 1-30, 31-60, 61-90, over 90 days) and the invoices still open.
// Sheet: a Ledger tab with a header row (Date, Customer, Type, Amount, plus optional
// Reference, Due date and Applies to) and an optional Customers tab (Customer, Email, Address).
// The script only reads those tabs; it writes to its own "Statement log" tab.
const FOLDER_ID = 'PASTE_DRIVE_FOLDER_ID';    // Drive folder for the PDFs
const LEDGER_SHEET = 'Ledger';
const CUSTOMERS_SHEET = 'Customers';            // optional: Email and Address per customer
const LOG_SHEET = 'Statement log';              // created on the first real run
const BUSINESS_NAME = 'Your business name';
const BUSINESS_LINES = ['Street address', 'billing@yourbusiness.example'];  // printed under the name
const CURRENCY = '$';
const TERMS_DAYS = 30;                          // due date for invoice rows with no Due date
const PERIOD_START = '';                        // 'yyyy-mm-dd', or '' = first day of last month
const PERIOD_END = '';                          // 'yyyy-mm-dd', or '' = last day of last month
const SKIP_ZERO = true;                         // no statement when the balance is 0 and nothing happened
const STATEMENT_NOTE = 'Please pay the amount due by each invoice\'s due date. Questions about this statement? Just reply.';
const EMAIL_STATEMENTS = false;                 // true = email each PDF to the customer's Email
const PREVIEW = true;                           // true = at most 3 PDFs named "PREVIEW ...", emails only to you, no log
const REPLY_TO = '';                            // optional reply-to address for customer emails
const MAX_PER_RUN = 25;                         // run again to continue; finished customers are skipped
const KEEP_DOCS = false;                        // false = keep only the PDF, not the Google Doc
const ADD_TYPES = ['invoice', 'charge', 'fee', 'debit'];                       // raise the balance
const SUB_TYPES = ['payment', 'credit', 'credit note', 'write-off', 'write off']; // lower it
const DAY = 86400000;
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

function onOpen() {
  SpreadsheetApp.getUi().createMenu('Statements')
    .addItem('Make customer statements', 'makeStatements')
    .addToUi();
}

function makeStatements(now) {
  let ui = null;
  if (!(now instanceof Date)) {          // run from the menu or a monthly trigger
    now = new Date();
    try { ui = SpreadsheetApp.getUi(); } catch (e) { ui = null; }   // no UI when a trigger runs it
  }
  const lock = LockService.getDocumentLock();
  if (!lock.tryLock(30000)) return;      // another run is still busy
  try {
    const result = run_(now);
    if (ui) ui.alert(summary_(result));
    return result;
  } finally {
    lock.releaseLock();
  }
}

function run_(now) {
  const ss = SpreadsheetApp.getActive();
  const tz = ss.getSpreadsheetTimeZone();
  const ledgerSheet = ss.getSheetByName(LEDGER_SHEET);
  if (!ledgerSheet) throw new Error('No tab named ' + LEDGER_SHEET + '.');
  const period = period_(dayNum_(Utilities.formatDate(now, tz, 'yyyy-MM-dd')));
  const ledger = readLedger_(ledgerSheet.getDataRange().getValues(), tz);
  const custSheet = ss.getSheetByName(CUSTOMERS_SHEET);
  const contacts = custSheet ? readCustomers_(custSheet.getDataRange().getValues()) : {};
  const accounts = buildAccounts_(ledger.rows, contacts, period);
  let log = ss.getSheetByName(LOG_SHEET);
  const done = PREVIEW || !log ? {} : readLog_(log.getDataRange().getValues(), tz);
  const endKey = key_(period.end);
  const todo = accounts.filter(function (a) { return !done[endKey + '|' + a.key]; });
  const res = { period: key_(period.start) + ' to ' + endKey, preview: PREVIEW, made: 0, emailed: 0,
    alreadyDone: accounts.length - todo.length, left: 0, quota: false, noEmail: [],
    skippedRows: ledger.skipped, pdfs: [] };
  if (!todo.length) return res;
  const folder = DriveApp.getFolderById(FOLDER_ID);
  const me = Session.getEffectiveUser().getEmail();
  const limit = PREVIEW ? Math.min(3, MAX_PER_RUN) : MAX_PER_RUN;
  for (let i = 0; i < todo.length; i++) {
    const a = todo[i];
    if (res.made >= limit) { res.left = todo.length - i; break; }
    const emails = EMAIL_STATEMENTS ? emails_(a.email) : null;
    const to = emails ? (PREVIEW ? [me] : emails) : [];
    if (to.length && MailApp.getRemainingDailyQuota() < to.length) {
      res.left = todo.length - i; res.quota = true; break;     // tomorrow's run continues here
    }
    const made = makePdf_(folder, a, period, PREVIEW ? 'PREVIEW ' : '');
    res.made++;
    res.pdfs.push(made.url);
    let note = EMAIL_STATEMENTS ? '' : 'emailing off';
    if (EMAIL_STATEMENTS && !emails) { res.noEmail.push(a.name); note = 'no valid Email'; }
    if (to.length) {
      MailApp.sendEmail(mail_(a, period, made.blob, to, emails));
      res.emailed++;
    }
    if (!PREVIEW) {
      if (!log) {
        log = ss.insertSheet(LOG_SHEET);
        log.appendRow(['Period end', 'Customer', 'Closing balance', 'PDF', 'Emailed to', 'Note', 'Made at']);
      }
      log.appendRow([endKey, a.name, a.closing / 100, made.url, to.length ? emails.join(', ') : '', note,
        Utilities.formatDate(now, tz, 'yyyy-MM-dd HH:mm')]);
      SpreadsheetApp.flush();             // the log survives even if a later customer fails
    }
  }
  return res;
}

// Statement period: PERIOD_START / PERIOD_END, or last calendar month.
function period_(today) {
  let start = PERIOD_START ? dayNum_(PERIOD_START) : null;
  let end = PERIOD_END ? dayNum_(PERIOD_END) : null;
  if ((PERIOD_START && start === null) || (PERIOD_END && end === null)) {
    throw new Error('Write PERIOD_START and PERIOD_END as yyyy-mm-dd, or leave them empty.');
  }
  const t = ymd_(today);
  if (end === null) end = Date.UTC(t.y, t.m - 1, 1) / DAY - 1;
  if (start === null) { const e = ymd_(end); start = Date.UTC(e.y, e.m - 1, 1) / DAY; }
  if (start > end) throw new Error('PERIOD_START is after PERIOD_END.');
  return { start: start, end: end };
}

function readLedger_(values, tz) {
  const col = finder_(values[0]);
  const c = { date: col('Date'), customer: col('Customer'), type: col('Type'), amount: col('Amount'),
    ref: col('Reference'), due: col('Due date'), applies: col('Applies to') };
  if (c.date < 0 || c.customer < 0 || c.type < 0 || c.amount < 0) {
    throw new Error('The ' + LEDGER_SHEET + ' tab needs Date, Customer, Type and Amount columns ' +
      '(Reference, Due date and Applies to are optional).');
  }
  const text = function (v, k) { return k < 0 ? '' : String(v[k] === null ? '' : v[k]).trim(); };
  const rows = [], skipped = [];
  for (let i = 1; i < values.length; i++) {
    const v = values[i];
    const customer = text(v, c.customer).replace(/\s+/g, ' ');
    const typeText = text(v, c.type);
    const rawAmount = text(v, c.amount);
    if (!customer && !typeText && !rawAmount) continue;          // blank row
    const why = function (reason) { skipped.push('row ' + (i + 1) + ': ' + reason); };
    if (!customer) { why('no Customer'); continue; }
    const type = typeText.toLowerCase().replace(/\s+/g, ' ');
    const sign = ADD_TYPES.indexOf(type) >= 0 ? 1 : SUB_TYPES.indexOf(type) >= 0 ? -1 : 0;
    if (!sign) { why('unknown Type "' + typeText + '"'); continue; }
    const day = toDay_(v[c.date], tz);
    if (day === null) { why('Date is not a date'); continue; }
    const amount = typeof v[c.amount] === 'number' ? v[c.amount] : number_(rawAmount);
    if (isNaN(amount)) { why('Amount is not a number'); continue; }
    if (amount < 0) { why('negative Amount (enter it as a positive number; the Type sets the direction)'); continue; }
    let due = null;
    if (sign > 0) {
      due = c.due >= 0 && text(v, c.due) ? toDay_(v[c.due], tz) : day + TERMS_DAYS;
      if (due === null) { why('Due date is not a date'); continue; }
    }
    rows.push({ row: i + 1, key: customer.toLowerCase(), name: customer, day: day, type: typeText,
      sign: sign, cents: Math.round(amount * 100), ref: text(v, c.ref), due: due,
      applies: text(v, c.applies), appliesKey: text(v, c.applies).toLowerCase() });
  }
  return { rows: rows, skipped: skipped };
}

function readCustomers_(values) {
  const col = finder_(values[0]);
  const c = { customer: col('Customer'), email: col('Email'), address: col('Address') };
  if (c.customer < 0) throw new Error('The ' + CUSTOMERS_SHEET + ' tab needs a Customer column.');
  const out = {};
  for (let i = 1; i < values.length; i++) {
    const name = String(values[i][c.customer]).trim().replace(/\s+/g, ' ');
    if (!name || out[name.toLowerCase()]) continue;               // first row per customer wins
    out[name.toLowerCase()] = {
      name: name,
      email: c.email < 0 ? '' : String(values[i][c.email]).trim(),
      address: c.address < 0 ? [] : String(values[i][c.address]).split(/\r?\n/)
        .map(function (s) { return s.trim(); }).filter(String)
    };
  }
  return out;
}

function readLog_(values, tz) {
  const done = {};
  for (let i = 1; i < values.length; i++) {
    const p = values[i][0];
    const k = p instanceof Date ? Utilities.formatDate(p, tz, 'yyyy-MM-dd') : String(p).trim();
    const name = String(values[i][1]).trim().replace(/\s+/g, ' ').toLowerCase();
    if (k && name) done[k + '|' + name] = true;
  }
  return done;
}

// One account per customer (names match ignoring case and extra spaces). Rows after the
// statement date are left out, so a statement for last month ignores this month's activity.
function buildAccounts_(rows, contacts, period) {
  const map = {};
  rows.forEach(function (r) {
    if (r.day > period.end) return;
    const a = map[r.key] || (map[r.key] = { key: r.key, name: r.name, opening: 0, lines: [], all: [] });
    a.all.push(r);
    if (r.day < period.start) a.opening += r.sign * r.cents;
    else a.lines.push(r);
  });
  return Object.keys(map).map(function (k) {
    const a = map[k];
    a.lines.sort(function (x, y) { return x.day - y.day || x.row - y.row; });
    let bal = a.opening;
    a.lines.forEach(function (r) { bal += r.sign * r.cents; r.balance = bal; });
    a.closing = bal;
    a.aging = age_(a.all, period.end);
    const c = contacts[k] || {};
    a.name = c.name || a.name;
    a.email = c.email || '';
    a.address = c.address || [];
    return a;
  }).filter(function (a) {
    return !SKIP_ZERO || a.closing !== 0 || a.lines.length > 0;
  }).sort(function (x, y) {
    return x.name.localeCompare(y.name, undefined, { sensitivity: 'base', numeric: true });
  });
}

// Which invoices are still open on the statement date. A payment or credit with "Applies to"
// pays that invoice first; the rest of it, and every unapplied payment, pays the oldest due
// invoices first. Whatever is left over is an unapplied credit.
function age_(rows, end) {
  const inv = rows.filter(function (r) { return r.sign > 0; }).map(function (r) {
    return { ref: r.ref, refKey: r.ref.toLowerCase(), type: r.type, day: r.day, due: r.due,
      cents: r.cents, open: r.cents, row: r.row };
  });
  let credit = 0;
  rows.filter(function (r) { return r.sign < 0; })
    .sort(function (x, y) { return x.day - y.day || x.row - y.row; })
    .forEach(function (p) {
      let left = p.cents;
      if (p.appliesKey) {
        inv.forEach(function (i) {
          if (left > 0 && i.open > 0 && i.refKey === p.appliesKey) {
            const x = Math.min(left, i.open); i.open -= x; left -= x;
          }
        });
      }
      credit += left;
    });
  inv.sort(function (a, b) { return a.due - b.due || a.day - b.day || a.row - b.row; });
  inv.forEach(function (i) { const x = Math.min(credit, i.open); i.open -= x; credit -= x; });
  const buckets = [0, 0, 0, 0, 0];      // current, 1-30, 31-60, 61-90, over 90 days past due
  const open = inv.filter(function (i) { return i.open > 0; });
  open.forEach(function (i) {
    i.late = Math.max(0, end - i.due);
    buckets[i.late === 0 ? 0 : i.late <= 30 ? 1 : i.late <= 60 ? 2 : i.late <= 90 ? 3 : 4] += i.open;
  });
  return { buckets: buckets, credit: credit, open: open };
}

function makePdf_(folder, a, period, prefix) {
  const name = prefix + 'Statement - ' + a.name.replace(/[\\\/:*?"<>|]/g, '-') + ' - ' + key_(period.end);
  const old = folder.getFilesByName(name + '.pdf');
  while (old.hasNext()) old.next().setTrashed(true);   // a re-made statement replaces the old PDF
  const doc = DocumentApp.create(name);
  const file = DriveApp.getFileById(doc.getId());
  file.moveTo(folder);
  render_(doc.getBody(), a, period);
  doc.saveAndClose();
  const blob = file.getAs('application/pdf').setName(name + '.pdf');
  const pdf = folder.createFile(blob);
  if (!KEEP_DOCS) file.setTrashed(true);
  return { name: name, blob: blob, url: pdf.getUrl() };
}

function render_(body, a, period) {
  const H = DocumentApp.ParagraphHeading;
  body.setMarginTop(54).setMarginBottom(54).setMarginLeft(54).setMarginRight(54);
  const first = body.getParagraphs()[0];
  first.setText(BUSINESS_NAME);
  first.setHeading(H.HEADING1);
  BUSINESS_LINES.forEach(function (line) { body.appendParagraph(line).setHeading(H.NORMAL); });
  body.appendParagraph('Statement of account').setHeading(H.HEADING2);
  const due = a.closing > 0 ? ['Amount due', money_(a.closing)]
    : a.closing < 0 ? ['Credit balance', money_(-a.closing) + ' (nothing to pay)'] : ['Balance', money_(0)];
  const info = [['Customer', a.name]];
  if (a.address.length) info.push(['Address', a.address.join('\n')]);
  info.push(['Statement date', show_(period.end)], ['Period', show_(period.start) + ' to ' + show_(period.end)], due);
  table_(body, info, [], false);

  body.appendParagraph('Account activity').setHeading(H.HEADING3);
  const act = [['Date', 'Type', 'Reference', 'Due', 'Charges', 'Payments and credits', 'Balance'],
    [show_(period.start), 'Opening balance', '', '', '', '', money_(a.opening)]];
  a.lines.forEach(function (r) {
    const ref = r.sign < 0 && r.applies ? (r.ref ? r.ref + ' (for ' + r.applies + ')' : 'For ' + r.applies) : r.ref;
    act.push([show_(r.day), r.type, ref, r.sign > 0 ? show_(r.due) : '',
      r.sign > 0 ? money_(r.cents) : '', r.sign < 0 ? money_(r.cents) : '', money_(r.balance)]);
  });
  act.push([show_(period.end), 'Closing balance', '', '', '', '', money_(a.closing)]);
  const t = table_(body, act, [4, 5, 6], true);
  t.getRow(act.length - 1).editAsText().setBold(true);

  body.appendParagraph('Aging on ' + show_(period.end)).setHeading(H.HEADING3);
  const b = a.aging.buckets;
  table_(body, [['Current', '1-30 days', '31-60 days', '61-90 days', 'Over 90 days', 'Total due'],
    b.map(money_).concat([money_(Math.max(0, a.closing))])], [0, 1, 2, 3, 4, 5], true);
  if (a.aging.credit > 0) {
    body.appendParagraph('Unapplied payments and credits: ' + money_(a.aging.credit) + '.').setHeading(H.NORMAL);
  }
  if (a.aging.open.length) {
    body.appendParagraph('Open invoices').setHeading(H.HEADING3);
    const rows = [['Reference', 'Type', 'Date', 'Due', 'Amount', 'Still open', 'Days past due']];
    a.aging.open.forEach(function (i) {
      rows.push([i.ref, i.type, show_(i.day), show_(i.due), money_(i.cents), money_(i.open), i.late ? String(i.late) : '']);
    });
    table_(body, rows, [4, 5, 6], true);
  }
  if (STATEMENT_NOTE) body.appendParagraph(STATEMENT_NOTE).setHeading(H.NORMAL);
}

function table_(body, cells, rightCols, boldHeader) {
  const t = body.appendTable(cells);
  if (boldHeader) t.getRow(0).editAsText().setBold(true);
  for (let r = 0; r < cells.length; r++) {
    rightCols.forEach(function (c) {
      t.getCell(r, c).getChild(0).asParagraph().setAlignment(DocumentApp.HorizontalAlignment.RIGHT);
    });
  }
  return t;
}

function mail_(a, period, blob, to, emails) {
  const overdue = a.aging.buckets[1] + a.aging.buckets[2] + a.aging.buckets[3] + a.aging.buckets[4];
  const status = a.closing > 0
    ? 'Amount due: ' + money_(a.closing) + (overdue ? ' (' + money_(overdue) + ' of it is past due)' : '') + '.'
    : a.closing < 0 ? 'Your account has a credit balance of ' + money_(-a.closing) + ', so there is nothing to pay.'
    : 'Your balance is zero. Thank you!';
  const m = {
    to: to.join(','),
    subject: (PREVIEW ? '[PREVIEW to ' + emails.join(', ') + '] ' : '') +
      'Statement of account from ' + BUSINESS_NAME + ', ' + show_(period.end),
    body: 'Hello,\n\nAttached is your statement of account for ' + show_(period.start) + ' to ' +
      show_(period.end) + '.\n\n' + status + '\n\n' + (STATEMENT_NOTE ? STATEMENT_NOTE + '\n\n' : '') + BUSINESS_NAME,
    name: BUSINESS_NAME,
    attachments: [blob]
  };
  if (REPLY_TO) m.replyTo = REPLY_TO;
  return m;
}

function summary_(r) {
  const out = [(r.preview ? 'PREVIEW: ' : '') + r.made + ' statement PDF(s) for ' + r.period + '.'];
  if (r.emailed) out.push(r.emailed + ' email(s) sent' + (r.preview ? ' to you.' : '.'));
  if (r.alreadyDone) out.push(r.alreadyDone + ' customer(s) already done for this period (see ' + LOG_SHEET + ').');
  if (r.left) out.push(r.left + ' more to go' + (r.preview ? ' in the real run.' : r.quota ? ': email quota used up, run again tomorrow.' : ': run again.'));
  if (r.noEmail.length) out.push('No valid Email for: ' + r.noEmail.join(', ') + ' (PDF made, not sent).');
  if (r.skippedRows.length) out.push('Ledger rows left out:\n' + r.skippedRows.slice(0, 15).join('\n') +
    (r.skippedRows.length > 15 ? '\n...and ' + (r.skippedRows.length - 15) + ' more' : ''));
  return out.join('\n\n');
}

// ---- small helpers ----
function finder_(header) {
  const h = (header || []).map(function (x) { return String(x).trim().toLowerCase(); });
  return function (name) { return h.indexOf(name.toLowerCase()); };
}

function emails_(s) {
  const list = String(s || '').split(/[,;]/).map(function (x) { return x.trim(); }).filter(String);
  const ok = list.length > 0 && list.every(function (x) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(x); });
  return ok ? list : null;
}

function number_(s) {
  const t = String(s).replace(/[\s,]/g, '').split(CURRENCY).join('');
  return /^-?\d+(\.\d+)?$/.test(t) ? Number(t) : NaN;
}

function toDay_(v, tz) {
  if (v instanceof Date) return isNaN(v.getTime()) ? null : dayNum_(Utilities.formatDate(v, tz, 'yyyy-MM-dd'));
  return typeof v === 'string' ? dayNum_(v.trim()) : null;
}

// Dates are whole days counted from 1970-01-01, so time zones and daylight saving can't shift them.
function dayNum_(s) {
  const m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(String(s));
  if (!m) return null;
  const n = Date.UTC(+m[1], +m[2] - 1, +m[3]) / DAY;
  const back = ymd_(n);
  return back.y === +m[1] && back.m === +m[2] && back.d === +m[3] ? n : null;
}

function ymd_(n) {
  const d = new Date(n * DAY);
  return { y: d.getUTCFullYear(), m: d.getUTCMonth() + 1, d: d.getUTCDate() };
}

function key_(n) {
  const t = ymd_(n);
  return t.y + '-' + String(t.m).padStart(2, '0') + '-' + String(t.d).padStart(2, '0');
}

function show_(n) {
  const t = ymd_(n);
  return MONTHS[t.m - 1] + ' ' + t.d + ', ' + t.y;
}

function money_(cents) {
  const abs = Math.abs(cents);
  const whole = String(Math.floor(abs / 100)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return (cents < 0 ? '-' : '') + CURRENCY + whole + '.' + String(abs % 100).padStart(2, '0');
}

When the previews look right, set PREVIEW = false and run it again for the real statements. To email them, also set EMAIL_STATEMENTS = true, and do one preview run first: in preview mode every email goes to you, with the real recipients in the subject. To make statements automatically, add a monthly trigger: in the Apps Script editor click Triggers › Add Trigger, choose makeStatements, Time-driven, Month timer, the 1st of the month and an early-morning hour. Google picks a time within the hour you choose (see installable triggers), and on the 1st the default period is the month that just ended.

What the script does

Tips and caveats

Want a designed statement or past-due letter per customer? SheetWeave (disclosure: we make it) is a Google Sheets add-on that fills a Google Docs template with each row's column values and saves a Doc, a PDF, or both in a Drive folder you choose, writing the links back to the row. Pointed at the Customers tab above, where each row already has the balance and aging columns, it makes one branded balance summary or past-due letter per customer from your own template. For the line-by-line activity table, use the script above. 14-day free trial, no credit card to start. SheetWeave is on the Google Workspace Marketplace.
See SheetWeave

Related Google Sheets guides

Instructions refer to Google Sheets, Google Docs, Google Drive and Apps Script as they worked on November 15, 2026, and to the Google pages cited as they stood that day. Not accounting, tax or legal advice, and not affiliated with Google. Google Sheets, Google Docs and Google Drive are trademarks of Google LLC. Check the statements against your own books before sending them. Questions or corrections: hello@loomwise.app.