Ravindra BagaleCourses & study guides मराठी Track your progress

12. Macros and VBA

Practice and Answer Key: An Office Script that Summarises Orders by Status

Goal of this practice: Write an Office Script that reads tblOrders, counts orders and adds up the amount for each status, and writes a fresh Summary sheet.

Suppose Salman runs the fictional Solapur and Pune dark stores. Every evening he wants a small Summary sheet: one row per order status with the number of orders and the total amount. The 10 orders are in a Table named tblOrders on the sheet Orders, saved in OneDrive for Business. All data is fictional practice data.

About this data. The rows in this practice on An Office Script that Summarises Orders by Status are made up. The people, shops and amounts are fictional, so you can try the steps safely. Any business name here is not a real company.
Order ID City Amount (₹) Status
BLK-1001 Pune 64 Delivered
BLK-1002 Nashik 270 Delivered
AMN-1003 Pune 110 Delivered
BLK-1004 Nagpur 240 Cancelled
AMN-1005 Kolhapur 232 Delivered
BLK-1006 Pune 150 Delivered
BLK-1007 Solapur 1299 Delivered
AMN-1008 Sambhaji Nagar 195 Returned
BLK-1009 Pune 220 Cancelled
BLK-1010 Nashik 90 Delivered

Exercise (one under the other):

  1. Open the workbook in Excel on the web and select Automate › New Script › Create in Code Editor.
  2. Get the table tblOrders and read the data rows with getRangeBetweenHeaderAndTotal().getValues().
  3. Find the positions of the Status and Amount columns with getColumnByName(…).getIndex().
  4. Loop over the rows and keep a count and a total for each status.
  5. Delete the Summary sheet if it exists, then add a new one.
  6. Write a header row (Status, Orders, Amount) and one row per status, A to Z, starting in A1.
  7. Return the number of statuses, run the script and check the result. Rename it Status Summary.

Expected result (check your numbers):

Status Orders Amount (₹)
Cancelled 2 460
Delivered 7 2215
Returned 1 195
(script returns) 3 —
Answer key (open after you try)
function main(workbook: ExcelScript.Workbook): number {
  const table = workbook.getTable("tblOrders");
  const values = table.getRangeBetweenHeaderAndTotal().getValues();
  const statusCol = table.getColumnByName("Status").getIndex();
  const amountCol = table.getColumnByName("Amount").getIndex();

  // Count orders and add up the amount for each status
  const counts: { [status: string]: number } = {};
  const amounts: { [status: string]: number } = {};
  for (const row of values) {
    const s = row[statusCol] as string;
    counts[s] = (counts[s] || 0) + 1;
    amounts[s] = (amounts[s] || 0) + (row[amountCol] as number);
  }

  // Start a fresh Summary sheet every time
  let sheet = workbook.getWorksheet("Summary");
  if (sheet) {
    sheet.delete();
  }
  sheet = workbook.addWorksheet("Summary");

  // Build the output rows, A to Z by status
  const output: (string | number)[][] = [["Status", "Orders", "Amount"]];
  for (const s of Object.keys(counts).sort()) {
    output.push([s, counts[s], amounts[s]]);
  }
  sheet.getRange("A1:C" + output.length).setValues(output);
  return output.length - 1;
}

Common mistakes:

What you see Why Fix
Error: cannot read property of undefined The table is not named tblOrders Check Table Design › Table Name
Amounts are joined like "64270…" instead of added The Amount values were read as text Make sure the Amount column holds numbers; use (row[amountCol] as number)
Running twice gives an error that the sheet name exists The old Summary sheet was not deleted first Keep the getWorksheet / delete lines before addWorksheet
The flow fails but the script works by hand The script uses getActiveWorksheet() Use getWorksheet("Orders") and getTable("tblOrders")
No Automate tab Licence or admin setting Check the version note in lesson 12.17 with your IT admin

Ravindra Bagale's rule: a script that you can run twice and get the same answer is a script you can schedule.