Introduction
setFormulas writes NETPRICE and PRICEBAND calls; custom functions validate inputs and return values. The application's entry point is demoFunctions(). Baseline limitation, as stated in the workshop: Blank gaps in Orders can misalign generated formula references; use contiguous rows.
Key building blocks: function parameters; Number(); validation; return; array mapping.
Practical use cases
Quotes, order forms and discount calculations.
Prerequisites
- How a spreadsheet formula like =SUM(A1:A3) works.
- Interactive Learning Mode: a modern browser. Nothing else.
- Real Workspace Build: a Google account.
Source data
| Item | Quantity | Price | Discount |
|---|---|---|---|
| Book | 2 | 25 | 0.1 |
| Course | 3 | 40 | 0.2 |
| Kit | 1 | 60 | 0 |
Setup in your own Google account
- Download 03-custom-spreadsheet-functions.zip (Code.gs, starter.csv, README).
- In Google Drive, create a lesson folder and a new Google Sheets file inside it.
- Rename the first tab to exactly
Orders, then File → Import → Upload starter.csv → Replace current sheet. - Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
- Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
- Check the result: Net prices 45, 96, 60; bands Low, High, High.
Folder strategy: the repository's V6 code uses the folder that contains the spreadsheet. The deck mentions a Workshop Info cell B2; V6 never reads it. See the discrepancy log.
Complete source code (Code.gs)
From 03-custom-spreadsheet-functions at commit 4a26d919, SHA-256 bb94f7994ddf. Unchanged.
// Custom Spreadsheet Functions
// Entry point: demoFunctions; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","demoFunctions").addToUi();}
function demoFunctions(){
// Install formulas in a separate sheet so the source remains unchanged.
const s=output('Results',['Net','Band'],input('Orders').map(()=>['',''])); input('Orders').forEach((r,i)=>{const n=i+2;s.getRange(n,1,1,2).setFormulas([[`=NETPRICE(Orders!B${n},Orders!C${n},Orders!D${n})`,`=PRICEBAND(A${n})`]]);});
}
function input(name) { const s=SpreadsheetApp.getActive().getSheetByName(name); if(!s) throw Error('Missing tab: '+name); return s.getDataRange().getValues().slice(1).filter(r=>r.some(v=>v!=='')); }
function output(name,headers,rows) { const ss=SpreadsheetApp.getActive(); const s=ss.getSheetByName(name)||ss.insertSheet(name); s.clearContents(); s.getRange(1,1,1,headers.length).setValues([headers]).setFontWeight('bold'); if(rows.length) s.getRange(2,1,rows.length,headers.length).setValues(rows.map(r=>r.map(v=>typeof v==='string' && /^[=+@-]/.test(v)?"'"+v:v))); s.setFrozenRows(1); return s; }
function num(v){if(v===''||!Number.isFinite(Number(v))) throw Error('Invalid number: '+v); return Number(v);}
// Pure custom functions: no Workspace service calls.
function NETPRICE(quantity,price,discount){const q=num(quantity),p=num(price),d=num(discount);if(q<0||p<0||d<0||d>1)throw Error('Invalid order');return q*p*(1-d);}
function PRICEBAND(net){return num(net)<50?'Low':'High';}
How the code works
Beginner explanation
demoFunctions() does not calculate anything itself. It writes formulas into a Results tab; Google Sheets then calls the custom functions NETPRICE and PRICEBAND for each row, just like built-in functions.
Technical explanation
Custom functions are plain top-level functions whose names can be used in formulas. They receive cell values (or 2D arrays for ranges), must be deterministic, and cannot call services that need authorization or modify the spreadsheet. demoFunctions() uses setFormulas() with A1 references built from the row index, which assumes contiguous rows.
Slide excerpt
This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.
function demoFunctions(){
// Install formulas in a separate sheet so the source remains unchanged.
const s=output('Results',['Net','Band'],input('Orders').map(()=>['',''])); input('Orders').forEach((r,i)=>{const n=i+2;s.getRange(n,1,1,2).setFormulas([[`=NETPRICE(Orders!B${n},Orders!C${n},Orders!D${n})`,`=PRICEBAND(A${n})`]]);});
}Common mistakes
- Calling SpreadsheetApp or setValue() inside a custom function; it is not allowed.
- Expecting a custom function to recalculate when data it does not reference changes.
- Leaving gaps in the data so position-based formulas point at the wrong row.
Run it and expected output
Choose Workshop → Run application (runs demoFunctions()). Expected: Net prices 45, 96, 60; bands Low, High, High.
Original workshop exercise
Set first discount to 0.2; net becomes 40 and band remains Low.
Troubleshooting and debugging
A discount of 150%
Someone entered 1.5 as a discount. One result cell now shows #ERROR!.
Fix: Enter a discount between 0 and 1 (0.2).
Throwing inside a custom function shows #ERROR! in that cell only, which is safer than returning a negative price.
A blank row breaks the formulas
A blank row was left between orders. The last result now shows #ERROR!.
Fix: Remove the blank row (keep Orders contiguous) and rerun.
This is the documented baseline limitation: formulas are generated by position. The extension fixes it with range arguments.
Extension activity: Accept whole ranges
Let NETPRICE accept equally sized ranges and return a column of results, so one formula can price every order.
Acceptance checks:
- Original single-cell formulas still return 45, 96, 60
- =NETPRICE(Orders!B2:B4,Orders!C2:C4,Orders!D2:D4) fills three rows
Original improvement idea from the workshop: Support equally sized range arguments and return a two-dimensional array.
Extension prompt
Update the existing app without removing working features. Support equally sized range arguments and return a two-dimensional array. Return complete updated files, explain changes and give regression tests. Automation option: Custom formulas recalculate on cell changes; no trigger needed. Keep this separate from the baseline exercise.
Automation considerations
No trigger is needed: custom formulas recalculate automatically when referenced cells change.
Workshop note: Custom formulas recalculate on cell changes; no trigger needed.
Build prompt from the workshop
Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 03: Custom Spreadsheet Functions. Input tab Orders, exact headers: Item, Quantity, Price, Discount. Implement pure custom function NETPRICE(quantity,price,discount), supporting scalar values and rejecting invalid input; demonstrate =NETPRICE(B2,C2,D2). Add a second function PRICEBAND(net) with Low below 50, High otherwise. Do not depend on Workshop Info or the Workshop Index. Provide complete copy-paste Code.gs (and HTML if required), exact setup/run steps, explain the main code blocks, and include a test matching this expected outcome: Net prices 45, 96, 60; bands Low, High, High. Preserve starter data, use batch operations where appropriate, handle errors, and never send email or delete files. For AI lessons use the supplied callGemini helper, treat input as untrusted, and validate outputs. Match the reference entry point demoFunctions and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/03-custom-spreadsheet-functions. Base version limitations: Blank gaps in Orders can misalign generated formula references; use contiguous rows.
Knowledge check
Which statement about custom functions is true?
- They cannot call services that require authorization, such as GmailApp
- They can write to any cell
- They must be called from a menu
Answer
They cannot call services that require authorization, such as GmailApp Correct: custom functions run with restricted permissions and must not change the spreadsheet.
What does =PRICEBAND(A2) return when A2 is 50?
- High
- Low
- #ERROR!
Answer
High Correct: the rule is num(net) < 50 ? Low : High, and 50 is not less than 50.
Why does demoFunctions() write formulas instead of calculated numbers?
- So the results update automatically when Orders changes
- Because setValues() cannot write numbers
- Formulas are faster to write
Answer
So the results update automatically when Orders changes Correct: formulas recalculate when their inputs change; static numbers would go stale.
A result cell shows #ERROR! with the message "Invalid order". Where should you look first?
- The Quantity, Price and Discount on that order row
- The Apps Script triggers page
- The PRICEBAND function
Answer
The Quantity, Price and Discount on that order row Correct: NETPRICE throws Invalid order for negative values or discounts outside 0–1.
A sales rep wants NETPRICE to look up today's exchange rate from an API. Good idea?
- Risky: custom functions should be fast and deterministic; fetch rates in a separate script and store them in a cell
- Yes, custom functions are ideal for API calls
- Only if Gemini writes it
Answer
Risky: custom functions should be fast and deterministic; fetch rates in a separate script and store them in a cell Correct: network calls make formulas slow and unpredictable and can hit quotas on every recalculation.
Five-minute presenter demonstration
Open the demo link (temporary workspace; saved learner work is not touched).
Opening hook: Raise your hand if you have ever done this by hand: Repeated pricing calculations invite formula mistakes. Let us make the spreadsheet do it.
- 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Orders tab and its headers: Item, Quantity, Price, Discount. Say what goes in and what should come out.
Narration: Repeated pricing calculations invite formula mistakes. Practical uses: Quotes, order forms and discount calculations. - 0:45–1:30 — Predict and run. Ask the room: Book: 2 × 25 with a 10% discount. What will NETPRICE return? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
Narration: Expected: Net prices 45, 96, 60; bands Low, High, High. - 1:30–3:00 — Explain the code. Click the Code tab. Select demoFunctions() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
Narration: demoFunctions() does not calculate anything itself. It writes formulas into a Results tab; Google Sheets then calls the custom functions NETPRICE and PRICEBAND for each row, just like built-in functions. - 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Select the Orders tab, click cell D2, type 0.2 in the formula bar and press Enter. Click ▶ Run application again.
Narration: Workshop challenge: Set first discount to 0.2; net becomes 40 and band remains Low. - 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: No trigger is needed: custom formulas recalculate automatically when referenced cells change.
Narration: Baseline limitation: Blank gaps in Orders can misalign generated formula references; use contiguous rows.
Closing takeaway: setFormulas writes NETPRICE and PRICEBAND calls; custom functions validate inputs and return values.