Automate your Excel tasks with Office Scripts: Calculate the total of values in a column depending on the criteria in another column

As a newcomer to TypeScript, I have set a goal for today - to calculate the total sum of cell values in one column of an Excel file based on values from another column.

In my Excel spreadsheet, the calendar weeks are listed in column U and their corresponding values are in column R. My aim is to add up all the values for each week (in columns R and U), and store the overall sum for each week within the Excel file.

I keep my Excel file on OneDrive online, with all my data securely stored there. By accessing the "Automate" Tab in Excel, I am able to utilize Office Scripts - which functions similarly to Excel VBA but employs the TypeScript programming language instead.

Below you will find screenshots illustrating my attempted approach and what progress I have made so far.

  1. This is how my data appears in the Excel file:

https://i.stack.imgur.com/bwT6r.png

  1. Here is my attempt at solving the issue using OfficeScripts. I explored utilizing a do-while loop.
function main(workbook: ExcelScript.Workbook)
{
  const sheet = workbook.getWorksheet('Sheet1'); 
  const range = sheet.getRange("A2:A6");
  const x: number = 1;
  let sum: number = 0;

  do 
  {
    if (sheet.getRange("A1").getOffsetRange(x,0) === '1')
    {
         sum = sum + sheet.getRange("A1").getOffsetRange(x,0);
    }
  } while(sheet.getRange("A").getColumn.);
}

For problem-solving reference, I consulted this StackOverflow post: VBA Code to sum values in one column based on the value in another column in excel

If you have any insights or suggestions on how to effectively tackle this issue, your input would be greatly appreciated. Thank you!

Answer №1

If you're looking to streamline your Excel functions, here's a helpful approach for extracting unique values and calculating totals in specific columns. The process begins by identifying the ranges for columns U and R on a designated sheet. Once these ranges are determined, the associated values are retrieved. Next, the unique values in column U (the calendar column) are isolated and stored in an array.

With the unique values at hand, the script iterates through each element of the array. During this iteration, comparisons are made between the current array element and the original calendar values. When a match is found, the corresponding sum column value for that row is added to a variable. This cumulative total, along with its unique identifier, is then stored in a Map object.

This process repeats until all unique calendar values have been processed. Once complete, the function returns the Map object containing the unique values and their respective totals. This streamlined method offers efficiency and clarity when working with Excel data sets.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Link to download an Excel spreadsheet

My server is capable of generating excel files dynamically, and I am utilizing AJAX to download these dynamic excel files. Upon successful completion in the callback function, I receive the data for the excel file. $.ajax({ url: exporting. ...

Is it possible to configure Nginx mime types within a Docker container?

My docker-compose.yml file looks like this: version: "1.0" services: web: container_name: webserver image: nginx volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro - ./frontend:/frontend ports: - "8001:80&qu ...

Angular2 encountering a lack of service provider issue

After finding the code snippet from a question on Stack Overflow titled Angular2 access global service without including it in every constructor, I have made some modifications to it: @Injectable() export class ApiService { constructor(public http: Http ...

What is the best way to indicate a particular element within a subdocument array has been altered in mongoose?

I have a specific structure in my Mongoose schema, shown as follows: let ChildSchema = new Schema({ name:String }); ChildSchema.pre('save', function(next){ if(this.isNew) /*this part works correctly upon creation*/; if(this.isModifi ...

Setting up Datatables using AngularJS

I am working on a controller that organizes song rankings based on sales data. Upon initialization, the controller automatically sends an HTTP GET request to retrieve all the songs needed for display (currently set at the top 20 songs). If I ever need to a ...

Regular expression for parsing any CSS font properties

Does anyone have a reliable regex to break down a css font string into its individual components? 12px arial italic bold sans-serif 12px/50px verdana etc ...

Allow users to zoom in and out on a specific section of the website similar to how it works on Google Maps

I am looking to implement a feature on my website similar to Google Maps. I want the top bar and side bars to remain fixed regardless of scrolling, whether using the normal scroll wheel or CTRL + scroll wheel. However, I would like the central part of the ...

Guide to pinpointing a location with Google Maps

I am currently working on setting up a contact page that includes Google Maps to show the location of a meeting place. Here is the code I am using: JavaScript (function(){ document.getElementById('map_canvas').style.display="block"; var ...

Discovering the type in Typescript by specifying a function parameter to an Interface

Consider this sample interface: interface MyInterface { x: AnotherThing; y: AnotherThingElse; } Suppose we make the following call: const obj: MyInterface = { x: {...}, y: {...}, } const fetchValue = (property: keyof MyInterface) => { ...

How can I convert an xlsx file to JSON using ExcelJS in Node.js?

https://github.com/guyonroche/exceljs I am a beginner with exceljs and just came across the description of exceljs on github. The description states: "Read, manipulate and write spreadsheet data and styles to XLSX and JSON." I am looking for a way to ...

Utilizando Typescript com Ionic 2 e AngularJS para autenticar através de um método de post na requisição HTTP e

Greetings and good afternoon to everyone. I hope you all are doing well. I am a beginner in AngularJS, currently using Visual Studio, Ionic 2, and TypeScript. I have successfully connected my app to a REST API in .NET and have implemented a token for tes ...

React 18 introduces a new feature, ReactDOMClient.createRoot(), which allows for hot module replacement with Webpack. This allows developers to update components in real time without

After upgrading React to version 18, I encountered a console error with my Webpack dev server when the hot module replacement triggers and injects new JavaScript code: Warning: You are calling ReactDOMClient.createRoot() on a container that has already be ...

Fetch data dynamically upon scrolling using an AJAX request

Instead of making an ajax call to load data, I want to do it on scroll. Here is the code I have: $.ajax({ type: 'GET', url: url, data: { get_param: 'value' }, dataType: ' ...

When I type text into the form field, JavaScript causes a disruption in the form

I'm attempting to implement a dual-stage user onboarding procedure. Initially, users will input the industry they belong to and then provide a description. Upon clicking submit, my intention is to conceal that portion of the form and reveal the "Creat ...

When trying to authorize my channel, the JSON data is coming back as a blank string

I've encountered an issue with my JavaScript code: Pusher is throwing the error message "JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ", indicating empty data. I have double-checked the broadcasting service provider ...

Guidelines for incorporating Angular variables into jQuery scripts

I have a form with an input field that dynamically generates a list of names using Angular. My goal is to turn each name into a clickable link that will submit the form with that specific name as the input value. <form method="POST" action="/results/" ...

Exploring innovative CSS/Javascript techniques for creating intricate drawings

When using browsers other than Internet Explorer, the <canvas> element allows for advanced drawing. However, in IE, drawing with <div> elements can be slow for anything more than basic tasks. Is there a way to do basic drawing in IE 5+ using o ...

Can InstanceType<T> be utilized with an abstract class?

My intention is to enable it to reference implementations rather than the abstract itself, all while exclusively depending on the definitions in the abstract interface. ...

Do not include any null or empty objects when assigning to an array in Mongoose

When using mongoose's find() or findOne() methods, the returned value will be [] and null, respectively, if the where conditions are not met. This can cause issues when assigning these values to an array. Currently, I am filtering out the null values ...

Preventing Duplicate Random Numbers in Vue 3 and JavaScript: A Guide

I've been working on creating a function that can iterate through an array of objects with names and IDs, randomize the array, and then return one filtered item to slots.value. The current spin function successfully loops through the randomized object ...