Custom Spreadsheet Functions
Repeated pricing calculations invite formula mistakes.
What this teaches
Create reusable spreadsheet calculations. Quotes, order forms and discount calculations.
Start without an account in the local application. Read/edit the input, predict a result, run the current source and verify output. A local document preview is not a real Google Doc; a fixture is not a live model response.
Input and expected result
Input tab: Orders. Entry function: demoFunctions().
| Item | Quantity | Price | Discount |
|---|---|---|---|
| Book | 2 | 25 | 0.1 |
| Course | 3 | 40 | 0.2 |
| Kit | 1 | 60 | 0 |
Expected baseline: Net prices 45, 96, 60; bands Low, High, High.
Exact Workspace setup
- Download and unzip this project. Use one separate bound script per lesson.
- Create a dedicated Drive folder. Create a native Google Sheet inside it, and import starter.csv into a tab named Orders. Check the exact headers above.
- Open the Sheet → Extensions → Apps Script. Paste finished Code.gs into the script editor. Save.
- Choose demoFunctions in the function selector → Run. Review actual requested permissions. Reload the Sheet for the Workshop menu.
- Compare output with the baseline above. Check generated documents/drafts manually. No email should be sent.
- Perform the original challenge, investigate a failure and test duplicate/partial runs before scheduling. Do not install a trigger just because one manual run succeeded.
Understand the implementation
setFormulas writes NETPRICE and PRICEBAND calls; custom functions validate inputs and return values.
Key operations: function parameters; Number(); validation; return; array mapping
Focused source spotlight
This is an excerpt, not a standalone script. The complete implementation follows.
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})`]]);});
}Complete Code.gs
// 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';}
Four guided activities
Discover and run
Repeated pricing calculations invite formula mistakes.
- Inspect the editable Orders table. The starter has 3 records.
- Write your predicted result in Prediction. Click Run application.
- Compare Output with: Net prices 45, 96, 60; bands Low, High, High.
- Click Verify baseline; explain one result in Notes.
Expected: Net prices 45, 96, 60; bands Low, High, High.
Understand and modify
Set first discount to 0.2; net becomes 40 and band remains Low.
- Open Source and read demoFunctions. Select the entry function in the walkthrough.
- Return to Application. Click Prepare original challenge to create a separate challenge starting state.
- For AI projects inspect the revised recorded fixture: this is supplied response data, not newly generated AI.
- Run application and use Verify challenge; approval/sidebar projects show extra required steps.
Expected: Set first discount to 0.2; net becomes 40 and band remains Low.
Investigate and repair
Discount exceeds one
- Save a snapshot if you want to keep your experiment.
- Click Inject investigation. Set the first Discount to 1.2.
- Run application and inspect Output and Execution trace. Some investigations produce wrong/stale content rather than exceptions.
- Repair it: Set Discount to 0.1, representing ten percent. Run again and explain the root cause.
Expected: NETPRICE checks the allowed range [0,1].
Extend and automate
Support equally sized range arguments and return a two-dimensional array.
- Open Prompts. Select Extend and adapt the requirement to your goal.
- Build the feature in Source or export the complete project to Apps Script.
- Retest baseline and original challenge before considering scheduling.
- Use Resources → Automation readiness. Custom formulas recalculate on cell changes; no trigger needed.
Expected: The baseline still works; independent extension checks are designed and reviewed by you.
Original exercise
Set first discount to 0.2; net becomes 40 and band remains Low.
Debugging and troubleshooting
Discount exceeds one
Set the first Discount to 1.2.
Hint 1
Check the exact input/response contract and identify the affected field.
Hint 2
setFormulas writes NETPRICE and PRICEBAND calls; custom functions validate inputs and return values.
Hint 3 and repair
Set Discount to 0.1, representing ten percent.
NETPRICE checks the allowed range [0,1].
Missing tab: check its exact name. Missing document: ensure unique native companion Docs share the Sheet’s dedicated folder. Authorization failure: review source and contact your administrator. Recorded response exhausted: add a new explicit fixture; no live AI is running. Invalid JSON: repair syntax before validating schema. Valid but unsupported content: compare each claim with source records.
Build prompt
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.
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.
Knowledge check and answer key
- Which input tab does demoFunctions read?
Answer
Orders
- Which function starts the original application?
Answer
demoFunctions
- What is the baseline output you must verify?
Answer
Net prices 45, 96, 60; bands Low, High, High.
- Does this project need runtime Gemini in the real Workspace baseline?
Answer
No; Gemini can help during development only.
- What limitation matters before scheduling?
Answer
Blank gaps in Orders can misalign generated formula references; use contiguous rows.
Safe automation
Custom formulas recalculate on cell changes; no trigger needed.
Blank gaps in Orders can misalign generated formula references; use contiguous rows.
Reflect and extend
Explain the transformation using one actual input row. Which incorrect value could still pass structural validation? What happens if the function runs twice or fails after creating one output? Write your explanation before building this extension: Support equally sized range arguments and return a two-dimensional array.
Source alignment
Physical slide 22; printed sequence 13 of 48. Reference source SHA-256 bb94f7994ddf07eac8e8866b038e31b09e4bc7e0387f0a9d883dca70a0438048.
Slide notes use Workshop Info B2. Verified repository resolves the active spreadsheet parent folder; this build follows the repository. Keep companion files in that dedicated lesson folder.
Pinned repository reference · Full source manifest
Five-minute presenter demonstration
0:00–0:45
Action: Open Input. Read Orders headers and first row.
Repeated pricing calculations invite formula mistakes. This application is useful for Quotes, order forms and discount calculations. We will run the verified reference code against fictional data.
0:45–1:30
Action: Ask for predictions. Click Run application, then Verify baseline.
Our baseline is Net prices 45, 96, 60; bands Low, High, High. The browser displays local results. It has not connected to Google or a model.
1:30–3:00
Action: Open Source. Select demoFunctions in the code walkthrough.
setFormulas writes NETPRICE and PRICEBAND calls; custom functions validate inputs and return values. The complete code is available to edit and download. The excerpt is not a standalone script.
3:00–4:15
Action: Click Prepare original challenge, inspect the changed inputs, and Run application. Complete extra review/sidebar steps if listed.
Set first discount to 0.2; net becomes 40 and band remains Low. For AI lessons we edit a recorded response as well as source data. That response must be checked, not trusted.
4:15–5:00
Action: Click Verify challenge. Open Guide and read Automation considerations.
The important limitation is: Blank gaps in Orders can misalign generated formula references; use contiguous rows. Before scheduling: Custom formulas recalculate on cell changes; no trigger needed. Explain the result yourself before moving on.