DiscoveryVIP / Apps Script AcademyHelp

27. Working with formulas

Module 6 · 20 minutes · Lesson 26; earlier service and JavaScript fundamentals

Open Interactive Lesson

Discover

How can you use working with formulas without changing the wrong data?

Predict

Which values or resources will change, and which should stay unchanged? Write your prediction before execution.

Understand

setFormula stores formula source for Sheets to evaluate. getFormula retrieves the source while getValue retrieves a computed result. The local adapter supports only SUM, AVERAGE and COUNT over a rectangular A1 range; other formulas are explicitly unsupported. Locale and separator differences must be checked in the real spreadsheet.

Example 1: Working automation

The sum includes all three amounts: 120 + 80 + 200 = 400.

function main() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sales");
  sheet.getRange("B6").setFormula("=SUM(B2:B4)");
  console.log(sheet.getRange("B6").getValue());
}
Important line explanations
Line 1: function main() {
Define a named block of instructions. Run Script calls main; helpers run only when called.
Line 2: const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sales");
Resolve the current workbook. A real standalone project needs openById with a configured ID instead.
Line 3: sheet.getRange("B6").setFormula("=SUM(B2:B4)");
Select a rectangular area. A1 letters name columns; row and numeric range coordinates start at one.
Line 4: console.log(sheet.getRange("B6").getValue());
Select a rectangular area. A1 letters name columns; row and numeric range coordinates start at one.
Line 5: }
Close the current block. Indentation makes scope and the function boundary visible.
Exact expected output and resource
{
  "logs": [
    "400"
  ],
  "error": null,
  "resource": "sheets",
  "value": {
    "People": [
      [
        "Name",
        "Status"
      ],
      [
        "Alex",
        "Pending"
      ],
      [
        "Jordan",
        "Pending"
      ],
      [
        "Morgan",
        "Pending"
      ]
    ],
    "Sales": [
      [
        "Customer",
        "Amount",
        "Approved"
      ],
      [
        "Alex",
        120,
        true
      ],
      [
        "Jordan",
        80,
        false
      ],
      [
        "Morgan",
        200,
        true
      ],
      [],
      [
        "",
        "=SUM(B2:B4)"
      ]
    ],
    "Tasks": [
      [
        "Task",
        "Status"
      ],
      [
        "Review invoice",
        "Open"
      ],
      [
        "Publish report",
        "Complete"
      ]
    ]
  }
}

Example 2: Investigate a reproducible failure

Predict the effect of =SUM(B2:B3) and identify the first mismatch. This example is intentionally faulty.

function main() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sales");
  sheet.getRange("B6").setFormula("=SUM(B2:B3)");
  console.log(sheet.getRange("B6").getValue());
}
Important line explanations
Line 1: function main() {
Define a named block of instructions. Run Script calls main; helpers run only when called.
Line 2: const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sales");
Resolve the current workbook. A real standalone project needs openById with a configured ID instead.
Line 3: sheet.getRange("B6").setFormula("=SUM(B2:B3)");
Select a rectangular area. A1 letters name columns; row and numeric range coordinates start at one.
Line 4: console.log(sheet.getRange("B6").getValue());
Select a rectangular area. A1 letters name columns; row and numeric range coordinates start at one.
Line 5: }
Close the current block. Indentation makes scope and the function boundary visible.
Exact expected output and resource
{
  "logs": [
    "200"
  ],
  "error": null,
  "resource": "sheets",
  "value": {
    "People": [
      [
        "Name",
        "Status"
      ],
      [
        "Alex",
        "Pending"
      ],
      [
        "Jordan",
        "Pending"
      ],
      [
        "Morgan",
        "Pending"
      ]
    ],
    "Sales": [
      [
        "Customer",
        "Amount",
        "Approved"
      ],
      [
        "Alex",
        120,
        true
      ],
      [
        "Jordan",
        80,
        false
      ],
      [
        "Morgan",
        200,
        true
      ],
      [],
      [
        "",
        "=SUM(B2:B3)"
      ]
    ],
    "Tasks": [
      [
        "Task",
        "Status"
      ],
      [
        "Review invoice",
        "Open"
      ],
      [
        "Publish report",
        "Complete"
      ]
    ]
  }
}

Example 3: Separate setup from execution and inspect repeat behavior

Call the same named operation twice. Compare outputs and resource counts to learn whether this operation is idempotent. Repeated creation is deliberately visible; real exports require a rerun policy.

function lessonAction() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sales");
  sheet.getRange("B6").setFormula("=SUM(B2:B4)");
  console.log(sheet.getRange("B6").getValue());
}
function main() {
  lessonAction();
  lessonAction();
}
Important line explanations
Line 1: function lessonAction() {
Define a named block of instructions. Run Script calls main; helpers run only when called.
Line 2: const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sales");
Resolve the current workbook. A real standalone project needs openById with a configured ID instead.
Line 3: sheet.getRange("B6").setFormula("=SUM(B2:B4)");
Select a rectangular area. A1 letters name columns; row and numeric range coordinates start at one.
Line 4: console.log(sheet.getRange("B6").getValue());
Select a rectangular area. A1 letters name columns; row and numeric range coordinates start at one.
Line 5: }
Close the current block. Indentation makes scope and the function boundary visible.
Line 6: function main() {
Define a named block of instructions. Run Script calls main; helpers run only when called.
Line 7: lessonAction();
Follow this operation using the surrounding named values. Compare the actual recorded state with the lesson’s specific explanation below.
Line 8: lessonAction();
Follow this operation using the surrounding named values. Compare the actual recorded state with the lesson’s specific explanation below.
Line 9: }
Close the current block. Indentation makes scope and the function boundary visible.
Exact expected output and resource
{
  "logs": [
    "400",
    "400"
  ],
  "error": null,
  "resource": "sheets",
  "value": {
    "People": [
      [
        "Name",
        "Status"
      ],
      [
        "Alex",
        "Pending"
      ],
      [
        "Jordan",
        "Pending"
      ],
      [
        "Morgan",
        "Pending"
      ]
    ],
    "Sales": [
      [
        "Customer",
        "Amount",
        "Approved"
      ],
      [
        "Alex",
        120,
        true
      ],
      [
        "Jordan",
        80,
        false
      ],
      [
        "Morgan",
        200,
        true
      ],
      [],
      [
        "",
        "=SUM(B2:B4)"
      ]
    ],
    "Tasks": [
      [
        "Task",
        "Status"
      ],
      [
        "Review invoice",
        "Open"
      ],
      [
        "Publish report",
        "Complete"
      ]
    ]
  }
}

Example 4: Add a diagnostic boundary around the operation

Observe start, successful completion or a rethrown failure. This optional professional pattern adds error context without swallowing the error or rolling back changes.

function lessonAction() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sales");
  sheet.getRange("B6").setFormula("=SUM(B2:B4)");
  console.log(sheet.getRange("B6").getValue());
}
function main() {
  console.log("Start: Working with formulas");
  try { lessonAction(); console.log("Completed operation"); }
  catch(error) { console.error("Failed operation: " + error.message); throw error; }
}
Important line explanations
Line 1: function lessonAction() {
Define a named block of instructions. Run Script calls main; helpers run only when called.
Line 2: const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sales");
Resolve the current workbook. A real standalone project needs openById with a configured ID instead.
Line 3: sheet.getRange("B6").setFormula("=SUM(B2:B4)");
Select a rectangular area. A1 letters name columns; row and numeric range coordinates start at one.
Line 4: console.log(sheet.getRange("B6").getValue());
Select a rectangular area. A1 letters name columns; row and numeric range coordinates start at one.
Line 5: }
Close the current block. Indentation makes scope and the function boundary visible.
Line 6: function main() {
Define a named block of instructions. Run Script calls main; helpers run only when called.
Line 7: console.log("Start: Working with formulas");
Record diagnostic evidence. A log does not grant permissions or prove a later side effect succeeded.
Line 8: try { lessonAction(); console.log("Completed operation"); }
Record diagnostic evidence. A log does not grant permissions or prove a later side effect succeeded.
Line 9: catch(error) { console.error("Failed operation: " + error.message); throw error; }
Record diagnostic evidence. A log does not grant permissions or prove a later side effect succeeded.
Line 10: }
Close the current block. Indentation makes scope and the function boundary visible.
Exact expected output and resource
{
  "logs": [
    "Start: Working with formulas",
    "400",
    "Completed operation"
  ],
  "error": null,
  "resource": "sheets",
  "value": {
    "People": [
      [
        "Name",
        "Status"
      ],
      [
        "Alex",
        "Pending"
      ],
      [
        "Jordan",
        "Pending"
      ],
      [
        "Morgan",
        "Pending"
      ]
    ],
    "Sales": [
      [
        "Customer",
        "Amount",
        "Approved"
      ],
      [
        "Alex",
        120,
        true
      ],
      [
        "Jordan",
        80,
        false
      ],
      [
        "Morgan",
        200,
        true
      ],
      [],
      [
        "",
        "=SUM(B2:B4)"
      ]
    ],
    "Tasks": [
      [
        "Task",
        "Status"
      ],
      [
        "Review invoice",
        "Open"
      ],
      [
        "Publish report",
        "Complete"
      ]
    ]
  }
}

Build and test

Repair the supplied script so that: The sum includes all three amounts: 120 + 80 + 200 = 400. Preserve other source data. Checks compare observable output and the named resource, not exact source text.

function main() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sales");
  sheet.getRange("B6").setFormula("=SUM(B2:B3)");
  console.log(sheet.getRange("B6").getValue());
}

Graduated hints

Hint 1

Inspect the operation containing =SUM(B2:B3). Compare it with the stated rule and the first mismatch.

Hint 2

The repair concerns =SUM(B2:B4). Change only the relevant argument, operator or method; rerun with fresh input.

Hint 3

The reference uses =SUM(B2:B4) where the broken source uses =SUM(B2:B3). Explain why before applying it.

Reference solution

function main() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sales");
  sheet.getRange("B6").setFormula("=SUM(B2:B4)");
  console.log(sheet.getRange("B6").getValue());
}

Explain and reflect

Which operation proves the intended result in working with formulas? Which wrong input would expose a weakness, and what would remain unchanged?

Adapt the input records and sheets output to a second realistic case. Write its expected result before running. Demonstrate one invalid case and explain whether the side effects should be rolled back or retried.

Troubleshooting

If the console is empty, inspect the sheets preview: this script may work through state changes. If the function is missing, select main. For a service error inspect the first failed timeline entry and its arguments. Use Manual unless investigating a trigger. Changing input data also changes the expected result; restore sample data before the authored checks.

Knowledge check

Explain the key method or operator. Give an exact output for a second input, plus one invalid case. Verify the result in the interactive lesson; written explanations need self or educator review.

Optional AI practice

Explain this concept using the source above. Help implement one small extension and define its tests. Review/debug the source using its actual expected output; cite real method references and never claim execution.

Transfer to Google and authorization guide

Next lesson: Data validation and dropdowns