Apps Script example · 12 min read

Calculate Quality Defect Rates and PPM: Copy-Paste Apps Script Pattern

Working calculate quality defect rates and ppm example in Apps Script—copy-paste code, common mistakes, and when to get it built professionally.

SpreadsheetAppTime-drivenQuality

Compute defect rate and PPM by SKU and shift from inspection inspected/defect counts. The workbook becomes the system of record; Apps Script owns the joins and business rules so analysts are not pasting monthly formulas.

Entry point `calcDefectRates` reads typed columns with SpreadsheetApp batch APIs. SpreadsheetApp is the primary service; Time-driven describes how you usually invoke it after authorization.

Keep thresholds (grace days, bands, alert emails, API keys) in Config cells or Script Properties so the same .gs file promotes from sandbox to production without code edits.

This page is technical only: sheet layout, edge cases, runnable code, deploy steps, and FAQs for calculate quality defect rates and ppm. No consulting pitch—just the pattern you can paste and harden.

Need this built? Hire a Google Apps Script developer →

Sheet / project setup

TabColumnsNotes
InspectionsDate, SKU, Shift, Inspected, DefectsSource
DefectRateSKU, Shift, PPM, FlagOutput

What this script does

calcDefectRates() compute defect rate and PPM by SKU and shift from inspection inspected/defect counts.

  • PPM = rate × 1e6
  • SKU×shift grain
  • OVER flag threshold

Prerequisites

Container-bound script on the workbook that contains the tabs in the setup table. Authorize SpreadsheetApp scopes on first run.

  • V8 runtime
  • Exact sheet names
  • Script timezone = ops timezone

Walkthrough

Aggregate inspected/defects by SKU|shift, compute rate and PPM, flag OVER when PPM exceeds threshold.

Paste the code, set Config/Properties, run calcDefectRates once, verify the output tab, then attach a Time-driven trigger.

Edge cases

Zero inspected yields rate 0; PPM threshold default 5000 is editable in code.

Testing

Use a sandbox copy with 3–5 known rows. Compute expected outputs for calculate quality defect rates and ppm offline, run calcDefectRates, and diff the output tab including one intentional bad row.

Hardening

Add LockService around multi-sheet writes if triggers can overlap. Log run timestamps. Keep API keys and alert emails in PropertiesService—not in shared cells.

Variations

Fork ideas: filter to one business unit, change grain (daily→weekly), or POST a summary payload after calcDefectRates succeeds.

Operations notes

Assign an owner for the output tab, document regenerate steps, and treat `calcDefectRates` as source of truth over ad-hoc cell formulas.

Full code: calcDefectRates()

Run calcDefectRates when source tabs are current. Edit sheet names and Config/Properties first.

function calcDefectRates(){
  const ss=SpreadsheetApp.getActive();
  const rows=ss.getSheetByName('Inspections').getDataRange().getValues().slice(1);
  const agg={};
  rows.forEach(r=>{
    const sku=String(r[1]), shift=String(r[2]);
    const key=sku+'|'+shift;
    if(!agg[key]) agg[key]={inspected:0,defects:0};
    agg[key].inspected+=Number(r[3])||0;
    agg[key].defects+=Number(r[4])||0;
  });
  const out=Object.keys(agg).map(k=>{
    const [sku,shift]=k.split('|');
    const a=agg[k];
    const rate=a.inspected? a.defects/a.inspected : 0;
    const ppm=rate*1e6;
    const flag=ppm>5000?'OVER':'OK';
    return [sku,shift,a.inspected,a.defects,rate,ppm,flag];
  });
  const sh=ss.getSheetByName('DefectRate');
  sh.clearContents();
  sh.appendRow(['SKU','Shift','Inspected','Defects','Rate','PPM','Flag']);
  if(out.length) sh.getRange(2,1,out.length+1,7).setValues(out);
}
  1. Line 1: Entry point — bind triggers to calcDefectRates.
  2. Line 3: Batch read; avoid per-cell getValue in loops.
  3. Line 23: Batch write output rows in one setValues call.
  4. Line 5: Rename sheet constants before production.
  5. Line 6: Rename sheet constants before production.

Deploy this example

  1. 01

    Open Apps Script

    In the bound spreadsheet: Extensions → Apps Script. For standalone projects, create one at script.google.com and link your Sheet by ID.

  2. 02

    Paste and save

    Add a .gs file, paste the code below, rename constants at the top (sheet names, column letters, API property keys), then save.

  3. 03

    Authorize once

    Run the main function from the editor. Accept OAuth scopes when prompted — triggers cannot run until authorization succeeds once.

  4. 04

    Add the trigger

    Triggers → Add trigger → choose the handler function and event (time-driven, on edit, or on form submit). Delete test triggers before production.

Before you run: calculate quality defect rates and ppm

  • 1Setup tabs exist with headers matching calcDefectRates
  • 2Dry-run on a copy workbook
  • 3Timezone verified
  • 4SpreadsheetApp authorization completed
  • 5Output spot-checked against hand calc
  • 6Time-driven trigger added only after validation
  • 7Owners + alert recipients documented

Frequently asked questions

At minimum the tabs listed in the setup table for Calculate Quality Defect Rates and PPM. Output tabs may be cleared each run—do not store source-of-truth data there.

Run from the Apps Script editor for dry runs. Production usually uses a Time-driven trigger after OAuth succeeds once.

Zero inspected yields rate 0; PPM threshold default 5000 is editable in code.

Per-cell calls burn quota and wall time. One read + one write keeps this pattern under the 6-minute execution cap longer.

PropertiesService (Script Properties) for API keys and alert inboxes. Config sheet is fine for non-secret thresholds.

Simple ratios maybe; calculate quality defect rates and ppm needs joins, branching, or side effects (email/Docs/API) that Apps Script handles cleanly.

Keep the .gs in clasp/git. Avoid divergent copies of formulas on the output tab—regenerate from the script.

Related examples

Want this wired into your real workflow?

I adapt these patterns to your Sheet structure, APIs, and triggers — deployed in your Google account. Fixed-scope quotes from $500 · free 30-min consult · quote within 24 hours.