Excel Lesson 44 – Automating Tasks | Dataplexa
Lesson 44 · Office Scripts Theory + Practical

Automating Tasks

Running a script manually by clicking Run is useful, but the real power of Office Scripts comes when scripts run automatically — on a schedule, when a form is submitted, when a file arrives in a folder, or when an email is received. Power Automate is the Microsoft 365 automation platform that makes this possible. It connects Office Scripts to hundreds of triggers and services, turning a standalone script into a fully automated, zero-touch workflow. This lesson covers how Power Automate connects to Office Scripts, how to set up a scheduled script run, how to pass data into and out of a script via a flow, and the most useful practical patterns.

How Power Automate Connects to Office Scripts

Power Automate is a workflow automation tool built into Microsoft 365. A flow is made up of a trigger (what starts it) and one or more actions (what it does). The Excel Online (Business) connector in Power Automate includes a "Run script" action that runs any Office Script stored in OneDrive. The script runs against a specified workbook in SharePoint or OneDrive, and the flow can pass values in and receive values back.

Power Automate Flow Structure
TRIGGER
What starts the flow
Examples: Recurrence (schedule) · When a form response is submitted · When an email arrives · When a file is created · HTTP request · Manual button
ACTION (optional) — Prepare data
Get data to pass into the script
e.g. Get form response values · Parse email body · Get SharePoint list item · Compose a date string
📄
ACTION — Excel Online: Run script
The Office Script runs here
Location: SharePoint site or OneDrive · Document library · File (the workbook) · Script (select from your library) · Parameters: values passed into the script · Result: values returned from the script
📤
ACTION (optional) — Use the result
What to do with script output
e.g. Send email with returned values · Post Teams message · Create SharePoint item · Log to another spreadsheet

Setting Up a Scheduled Script Run

The most common Power Automate pattern for Excel automation is a scheduled flow: the script runs at a fixed time — every morning at 7am, every Monday, the first of every month — and processes the workbook without anyone needing to open it or click anything. This is how report preparation, data formatting, and summary updates are typically automated.

Building a scheduled flow in Power Automate:

1. Go to make.powerautomate.com
2. Create → Scheduled cloud flow
3. Set the schedule: start date, repeat interval (hourly / daily / weekly / monthly)
4. Add a step: + New step → search "Excel Online (Business)"
5. Choose action: "Run script"
6. Configure the action:
   Location:          SharePoint (or OneDrive for Business)
   Document Library:  Documents (or the library containing the file)
   File:              Browse to your workbook (.xlsx)
   Script:            Select from your script library

That is the complete flow for a simple scheduled run.
No parameters needed if the script reads data from the workbook directly.

Example use cases:
  ✓ Format and timestamp a weekly data dump every Monday 6am
  ✓ Calculate a monthly summary and write it to a Summary sheet
  ✓ Clear a staging table and flag it as ready for new data
  ✓ Archive the current week's rows to a History sheet and clear the active table
Scheduled Flow — Power Automate Configuration Panel
Run Script — Excel Online (Business)
Location
SharePoint
Document Library
Shared Documents
File
/Reports/Weekly-Sales.xlsx
Script
Format Weekly Report
Parameters
(none — script reads from workbook directly)
✓ Flow runs every Monday at 06:00 · no manual action required

Passing Data Into a Script From a Flow

A script can accept parameters from the flow — values that Power Automate passes in at runtime, such as a date, a name, a number, or a status value. This makes a single script reusable across many contexts: the same formatting script can receive a different sheet name each time it runs, or the same data entry script can receive different values from different form responses.

Declaring parameters in the script:

// Parameters are declared as additional arguments in the main function
// after the workbook parameter. Power Automate detects them automatically.

function main(
  workbook:   ExcelScript.Workbook,
  reportDate: string,    // passed in from the flow
  region:     string,    // passed in from the flow
  targetRows: number     // passed in from the flow
) {
  const sheet = workbook.getActiveSheet();

  // Use the parameters directly
  sheet.getRange("A1").setValue("Report Date: " + reportDate);
  sheet.getRange("B1").setValue("Region: " + region);

  console.log("Processing " + targetRows + " rows for " + region);
}

In Power Automate:
  After selecting the script, Power Automate detects the parameters
  and shows input fields for each one automatically.
  You can type a static value or use dynamic content from earlier
  in the flow (e.g. the form submission date, the email sender name).

Supported parameter types:
  string  → Text input in the flow
  number  → Number input in the flow
  boolean → Yes/No toggle in the flow
  string[] → Array of strings (passed as JSON)
Flow passes reportDate = "2025-03-10", region = "North", targetRows = 47 → script writes "Report Date: 2025-03-10" to A1, "Region: North" to B1, logs "Processing 47 rows for North"

This parameter pattern is what allows one script to do the work of many. Instead of writing a separate formatting script for each region's report, you write one script that accepts a region parameter and Power Automate calls it with a different region value each time. You can even loop through a list of regions in Power Automate using the "Apply to each" action, calling the same script once per region in a single flow run.

Returning Data From a Script to a Flow

Scripts can return values back to Power Automate — a count of rows processed, a calculated total, a status message, or a full dataset as JSON. The returned value becomes available as dynamic content in the flow for use in subsequent actions like sending an email or posting a Teams message.

Returning a value from a script:

// Change the function return type from void to the type you want to return

function main(workbook: ExcelScript.Workbook): string {
  const sheet     = workbook.getActiveSheet();
  const usedRange = sheet.getUsedRange();
  const rowCount  = usedRange.getRowCount() - 1; // subtract header row

  // Process the data...
  let urgentCount = 0;
  const values = usedRange.getValues();
  for (let i = 1; i <= rowCount; i++) {
    if (values[i][4] === "Overdue") urgentCount++;
  }

  // Return a summary string
  return urgentCount + " overdue rows found out of " + rowCount + " total.";
}

Returning an object (use JSON.stringify):

function main(workbook: ExcelScript.Workbook): string {
  const sheet  = workbook.getActiveSheet();
  const result = {
    rowCount:     100,
    urgentCount:  12,
    reportDate:   "2025-03-10",
    status:       "complete"
  };
  return JSON.stringify(result);
  // Power Automate receives this as a JSON string
  // Use the "Parse JSON" action in the flow to extract individual fields
}

In Power Automate, the return value appears as:
  result → body → result (in the "Run script" action output)
  You can use this value in Send an email, Post a Teams message, etc.
Return Value Flow — Script Output to Teams Message
Run Script
Returns:
"12 overdue rows found out of 100 total."
Condition
result contains
"overdue" → true
Post Teams Message
"⚠ Weekly report:
[script result]"

Three Practical Automation Patterns

Pattern 1 — Daily report formatter (Scheduled):
  Trigger:  Recurrence — every weekday at 06:30
  Action:   Run script "Format Daily Report" on Sales.xlsx
  No parameters, no return value needed
  The script formats the sheet, adds the date stamp, auto-fits columns

Pattern 2 — Form to spreadsheet (Event-triggered):
  Trigger:  Microsoft Forms — "When a new response is submitted"
  Action 1: Get response details (Forms connector)
  Action 2: Run script "Add Form Response" on Tracker.xlsx
            Parameters: name (string), email (string), score (number)
  Script appends a new row to the Responses table with the form data

  Script that receives and uses the parameters:
  function main(
    workbook: ExcelScript.Workbook,
    name:  string,
    email: string,
    score: number
  ) {
    const sheet = workbook.getActiveSheet();
    const table = sheet.getTable("Responses");
    const today = new Date().toISOString().split("T")[0]; // "2025-03-10"
    table.addRow(-1, [today, name, email, score]);
  }

Pattern 3 — Exception alert (Scheduled + conditional email):
  Trigger:  Recurrence — every Monday at 08:00
  Action 1: Run script "Count Overdue" on Orders.xlsx (returns a string)
  Action 2: Condition — if script result contains "0 overdue"
            Yes: do nothing (terminate)
            No: Send email to manager with the script result in the body

Pattern 3 is particularly useful for exception-based reporting. Instead of a manager reviewing a spreadsheet every Monday to check for overdue items, the flow checks automatically and only sends an email when there is actually something to act on. Zero-noise automation that surfaces the right information at the right time is far more valuable than a report that arrives regardless of whether it contains anything actionable.

💡 Teacher's Note
One requirement that catches people out when setting up Power Automate flows with Office Scripts: the workbook must be stored on SharePoint or OneDrive for Business, not on a local drive or a personal OneDrive. Power Automate accesses files through the Microsoft 365 cloud infrastructure, so the workbook needs to be in a location the flow can reach. If your organisation stores files on SharePoint team sites, that is your best target location. Also check that the account running the flow (usually the flow owner's account) has edit access to the workbook — the script runs under that account's permissions, not a shared service account. Access errors are the single most common cause of flow failures on first setup.

🠐 Practice

Q1. You want to run an Office Script every weekday morning at 7am without any manual action. What type of Power Automate trigger do you use?




Q2. Write the function signature for an Office Script that accepts a sheetName (string) and a targetDate (string) parameter from Power Automate.




Q3. A script returns a JSON string using JSON.stringify(). In Power Automate, what action do you use after "Run script" to extract individual fields from that JSON string?



🟣 Quiz

Q1. Where must the Excel workbook be stored for a Power Automate flow to run an Office Script against it?







Q2. How does Power Automate know what parameters a script accepts?







Q3. You want a flow that only sends a Teams notification when a script finds overdue rows, and stays silent when there are none. What Power Automate action do you add after "Run script" to make this conditional?






Next up — Advanced Scripts Project, where we bring together everything from Section VII to build a complete automated workflow: a script that processes a data table, flags exceptions, and triggers a Power Automate flow that emails a formatted summary report.