A spreadsheet script is a small program attached to a workbook. It reads values from cells, runs calculations, builds an output such as a summary or a report, and sends that output on a schedule or when something changes. Scripts remove the weekly copy-paste routine, but they only work well when the formulas underneath them are sound. A script that sends a report built on a fragile formula will send the wrong number, reliably, every Monday.
This guide covers how scripts run, how to choose a platform, which formulas the script depends on, the mistakes that cause most failures, the costs and limits, and a worked example that sends a weekly summary by email.
Glossary and orientation
The terms below are used throughout this guide.
- Script: Code that performs actions in a spreadsheet, such as reading ranges, writing values or sending email.
- Function (spreadsheet): A built-in calculation entered in a cell, such as
SUMIFSorXLOOKUP. Not to be confused with a function inside a script. - Trigger: The condition that starts a script. Common types are time-driven (for example, every Monday at 07:00), edit-driven (when a cell changes) and manual (a button or menu item).
- Range: A block of cells, such as
A2:C50. - Authorisation: The one-time permission a user grants so a script can access the file, send email or use other services.
- Quota: A daily limit set by the platform, such as the number of emails a script may send.
- Macro: A recorded or written set of actions, most often associated with Excel’s VBA language.
Skip the setup
Generate invoices from a client list and see who has paid, who hasn’t and how late they are.
SOP 1.0 — How a spreadsheet script runs
Every scheduled script follows the same sequence. Understanding the sequence makes faults easier to locate.
- The trigger fires at the scheduled time or in response to an event.
- The script opens the named workbook and sheet, and stops with an error if either is missing.
- The script reads values from defined ranges.
- The script builds the output, either as a plain-text body, an HTML table or a file attachment.
- The script sends the output through the mail service or writes it to another location.
- The script records what it did, usually in a log sheet, so a later check can confirm the run.
Most failures happen at step 2 or step 3. A renamed tab or a moved column breaks the script without any visible warning in the spreadsheet itself. Naming ranges and checking for the expected sheet name at the top of the script prevents much of this.
SOP 2.0 — Choosing a platform
There are three realistic choices for most business users. The right one depends on where the workbook lives and who has to maintain the script.
| Factor | Google Apps Script (Google Sheets) | Office Scripts with Power Automate (Excel for the web) | VBA macros (Excel desktop) |
|---|---|---|---|
| Language | JavaScript | TypeScript | VBA |
| Where it runs | Google’s servers | Microsoft’s servers, triggered by Power Automate | On the user’s own computer |
| Typical trigger | Time-driven, edit-driven, form submission | Scheduled or event-driven flow | Button, workbook open, or timer via other tools |
| Sends email natively | Yes, through the mail service | Yes, through Outlook connectors in a flow | Yes, through Outlook automation |
| Licence needed | Free with a Google account; Workspace accounts have higher limits | Microsoft 365 licence, plus Power Automate access | Excel desktop; no extra cost, but macros may be blocked |
| Main risk | Daily sending and runtime quotas | Connector and licensing complexity | Macro security settings and file format (.xlsm) |
A few practical points follow from the table.
- If the workbook is in Google Sheets, use Apps Script. Adding a second tool creates an extra system to maintain.
- If the organisation runs Microsoft 365 and the workbook lives in SharePoint or OneDrive, Office Scripts with Power Automate is usually the cleaner route, because the script and the flow sit in the same tenant and are easier to audit.
- VBA still runs many older processes, but many organisations block macros in email attachments and on shared drives. Plan for that before building anything that depends on it.
SOP 3.0 — Formulas the script depends on
Scripts and formulas do different jobs. Formulas do the calculating inside the sheet, where anyone can see them. Scripts move results around and act on them. The practical rule is simple: put the logic in formulas wherever possible, then let the script read the answers.
The functions below appear most often in automated reporting.
SUMIFStotals values that meet one or more conditions. For example,=SUMIFS(C:C, A:A, "North", B:B, ">="&DATE(2024,1,1))totals column C for the North region from 1 January 2024. Use it instead of helper columns where possible.XLOOKUP(Excel 365 and recent Google Sheets) orINDEXwithMATCH(older versions and maximum compatibility) returns a value from one column based on a match in another.XLOOKUPis easier to read;INDEX/MATCHworks in every version.FILTERreturns only the rows that meet a condition, which is useful when a report needs a live list of overdue invoices or open orders.UNIQUEreturns a distinct list, which lets the script build a list of recipients or categories without manual upkeep.QUERY(Google Sheets only) applies SQL-like filtering and grouping in one formula. It is powerful, but its syntax is unforgiving, so keep a note of what each query is meant to return.IFERRORorIFNAreplaces an error with a fallback value. Use them with care. A fallback of zero can hide a missing lookup and send an incorrect total.TEXTformats numbers and dates for display, such as=TEXT(B7,"£#,##0.00").
One habit matters more than any single function. Give every output cell a fixed, labelled location, such as a sheet named Summary with the total in B7. The script can then read a known cell. A script that searches for “the total somewhere in column B” will eventually read the wrong number.
When the script reads a formula result, use getValues() or getDisplayValues(). Use getFormulas() only when you need to check or copy the formula text itself. Reading the formula text instead of the result is a common reason a script sends a formula string where a number should be.
SOP 4.0 — Common mistakes and how to avoid them
Most failed automations trace back to a short list of causes. Review this list before deploying any script.
- Hard-coded row numbers. A range such as
A2:C5is correct until someone adds a row. Use a defined end point, or compute the last row withgetLastRow(), and document the choice. - Renamed or moved sheets. A script that refers to
"Summary"fails silently if the tab is renamed to"Summary (old)". Check for the sheet at the start of the script and throw a clear error if it is missing. - Blank data sent as a report. An empty range produces an email that says “Total: 0”, which looks like a real result. Check that the key cells contain data before sending.
- Triggers duplicated during editing. Each time a time-driven trigger is created, it runs again. A script with two identical weekly triggers sends two emails. Check the triggers list before testing.
- Testing with live recipients. Run the first versions against a test address, not the distribution list.
- Changing formulas without checking the script. A column that moves or a formula that returns text instead of a number breaks the script’s assumptions. Keep a short change note in the workbook.
- Storing credentials or personal data in the code. Keep recipient addresses in a clearly labelled constant or a settings sheet, and avoid pasting customer records into the script editor.
Ready-made template
Every client, lead and follow-up in one sheet, with drop-downs and status colours already set up.
SOP 6.0 — Edge cases to plan for
These cases do not arise on the first day, but they arise in most working workbooks within a year.
- Empty periods. A weekly report for a week with no sales should say so. Build the message so that a zero or blank state reads as an explicit result, not as an error.
- Time zones. Triggers run in the time zone of the script’s settings, which may differ from the team’s. Set the project time zone deliberately, and check which zone the date formulas use.
- Currency and locale. A decimal comma in one region and a decimal point in another can turn
1.250into a different number. Format values withTEXTorgetDisplayValues()in one place. - Large ranges. Reading an entire column for every run is slow. Read only the range the report needs, and keep the data source tidy.
- Email size and format. Long HTML tables can be clipped by some mail clients. Attachments above the mail service’s size limit fail without a useful message. Send a link to the file in a shared folder for large outputs.
- Permission changes. If the account that owns the script leaves the organisation, the triggers may stop. Transfer ownership of the script and the file before that happens.
- Concurrent edits. A script that writes to a sheet while someone is editing it can overwrite a change. Write to a separate output sheet, not to the input data.
- Failure notices. A script that fails quietly is worse than no script. Add a
try/catchblock that emails an administrator when a run fails, so the failure is seen the same day.
SOP 7.0 — Worked example: weekly sales summary in Google Sheets
This example sends a summary every Monday at 07:00. It assumes a workbook with a sheet named Summary containing region names in A2:A5, weekly unit counts in B2:B5, revenue in C2:C5, and a total revenue figure in C7. The totals are calculated by formulas, such as =SUMIFS on the raw sales sheet, so the script only reads results.
Step 1: Prepare the sheet
- Create the
Summarysheet with the layout described above. - Enter the region labels in
A2:A5. - Enter the formulas that calculate units and revenue. For example, in
B2:=SUMIFS(Sales!D:D, Sales!B:B, A2, Sales!A:A, ">="&(TODAY()-7)). - Enter the total revenue in
C7:=SUM(C2:C5). - Check the sheet by hand. Confirm that the figures match the raw data before automating anything.
Step 2: Add the script
Open the workbook, choose Extensions, then Apps Script. Replace the default code with the following.
const REPORT_SHEET = 'Summary';
const RECIPIENTS = 'sales-leads@example.com';
const ADMIN_EMAIL = 'ops-admin@example.com';
function sendWeeklySalesReport() {
try {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(REPORT_SHEET);
if (!sheet) {
throw new Error('Sheet "' + REPORT_SHEET + '" not found.');
}
const rows = sheet.getRange('A2:C5').getDisplayValues();
const total = sheet.getRange('C7').getDisplayValue();
if (rows[0][0] === '' || total === '') {
throw new Error('Report data is empty. Email not sent.');
}
let body = 'Weekly sales summary\n\n';
rows.forEach(function (row) {
body += row[0] + ': ' + row[1] + ' units, ' + row[2] + ' revenue\n';
});
body += '\nTotal revenue: ' + total;
MailApp.sendEmail(RECIPIENTS, 'Weekly sales summary', body);
} catch (error) {
MailApp.sendEmail(ADMIN_EMAIL, 'Weekly sales report failed', error.message);
throw error;
}
}
The script does four things that the earlier SOPs required. It checks that the sheet exists, reads display values so the text matches what people see, stops if the data is blank, and emails an administrator when something goes wrong.
Step 3: Test the script
- Change
RECIPIENTSto your own address. - Click Run and choose
sendWeeklySalesReport. - When prompted, review the permissions and grant authorisation. Apps Script will ask for access to the spreadsheet and to send email.
- Check your inbox. Confirm the figures match the sheet.
- Rename the
Summarytab temporarily and run the script again. Confirm that the administrator receives the failure notice, then restore the name. - Change
RECIPIENTSback to the live group address.
Step 4: Set the trigger
- In the Apps Script editor, open Triggers (the clock icon in the left menu).
- Select Add Trigger.
- Set the function to
sendWeeklySalesReport, the event source to Time-driven, the type to Week timer, the day to Monday, and the time to 7am to 8am. - Save, and confirm there is exactly one trigger for this function.
Step 5: Hand over
Write a short note in the workbook, on a sheet named Notes. Record the owner, the date of last change, the recipient group, the trigger schedule, and the name of the administrator who receives failure notices. This note is the difference between a script that survives a staff change and one that stops without anyone knowing why.
Frequently asked questions
Can a script run without anyone opening the file?
Yes. Time-driven triggers run on the platform’s servers. The workbook must still exist and the authorising account must still have access.
Do I need to know how to code?
For a simple report like the one above, you need to read and adjust code, not write it from scratch. For anything with branches, loops across many sheets or external data, a developer should own the script.
Should the script do the calculations?
Usually not. Keep calculations in formulas, where anyone can audit them. Use the script for movement, formatting and delivery.
What if the report must go to many recipients with different content?
Build one output per recipient group, or use a mail merge process. Avoid one script that loops through hundreds of individual emails, because it will hit sending limits and is hard to check.
Decision rule
Automate a process when it repeats at least weekly, its inputs live in fixed locations, and someone is willing to own it. If any of those conditions is missing, fix the formulas and the layout first. A script built on an unstable workbook only automates the instability.
