Modifying the color of multiple cells simultaneously

I'm currently facing an issue where I need to change the cell color of multiple cells at once, all stored within a specific range. However, I only want certain cells to change based on a particular condition. While I can manually change each cell, it's time-consuming and inefficient. I am thinking that if I can construct a range of cells, I could use the setBackground() command for better efficiency.

Therefore, I'm seeking advice on the most effective way to tackle this problem?

The approach I am considering involves:

  • Utilizing a range.
  • Recognizing that ranges contain a "block" of cells, including some that may not require color changes.
  • Exploring the possibility of removing unwanted cells from a range. If achievable, I could iterate through and exclude those unnecessary cells before applying changes to the rest.
  • Potentially storing cells in an array and creating a range from that. However, this idea is hindered by my understanding that ranges typically consist of a rectangular block with two corner cells and contents in between.
  • Investigating alternative constructs that can handle multiple cells simultaneously, akin to a range’s capabilities.

Here is my current loop logic:

  for(var i=1; i<=numRows; i++){
    for(var j=1; j<=numColumns; j++){
      var mCell = monthRange.getCell(i, j);
      var mValue = mCell.getValue();
      if(mValue != "")
      {
        var eCell = exerciseRange.getCell(1, mValue);
        var eValue = eCell.getValue();
      }
      
      if (mValue != "" && eValue == true) {
        mCell.setBackground('green');
      } 
    }
  }

I would greatly appreciate any assistance as I navigate this challenge, especially since I am relatively new to this concept.

Thanks! TM

Answer №1

Optimize your code by fetching all the ranges, values, and backgrounds at once and storing them as arrays. Then iterate through the arrays to make comparisons and store the backgrounds in a separate array. Set the backgrounds only once after completing all comparisons:

function optimizeFunction() {
  var sheet = SpreadsheetApp.getActive();
  var monthRange = sheet.getRange("A1:C50000");
  var monthValues = monthRange.getValues(); // retrieve range values as an array

  var exerciseRange = sheet.getRange("D1:K1");
  var exerciseValues = exerciseRange.getValues(); //fetch exercise range values as an array

  var numColumns = monthRange.getNumColumns();
  var numRows = monthRange.getNumRows();
  var backgrounds = monthRange.getBackgrounds(); // fetch backgrounds as an array

  for (var i = 0; i < numRows; i++) {
    for (var j = 0; j < numColumns; j++) {
      var mValue = monthValues[i][j]; // access value from values array
      if (mValue != "") {
        var eValue = exerciseValues[0][mValue-1]; // access corresponding exercise value
        if (eValue == true) {
          backgrounds[i][j] = "green"; // update background color in array
        }
      }
    }
  }

  monthRange.setBackgrounds(backgrounds); // set all backgrounds at once

}

Try this optimized version which processed 150,000 cells (50,000 rows * 3 columns) in just 15 seconds!

https://i.sstatic.net/9K87L.png

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

Transfer information from .gs (Google Apps Script) to a variable inside a <script> tag in an HTML document

[ {"id":1,"label":"Node 2"}, {"id":2,"label":"Node 3"}, {"id":3,"label":"Node 4"}, {"id":4,"label":"Node 5"} ] Hello there! The function getArray() in the code snippet above is returning the specified string ↑. I need help connecting this data w ...

The initial JavaScript load shared by all users is quite large in the next.js framework

Currently working on a project using the Next.js framework and facing an issue where the First Load JS shared by all pages is quite heavy. I am looking for advice on possible strategies to reduce the weight of the JS file, and also wondering if there ...

The error message "MVC JS deletethisproduct is not defined at HTMLAnchorElement.onclick (VM457 Index:40)" indicates that there

Upon clicking the button, I encounter this error: "deletethisproduct is not defined at HTMLAnchorElement.onclick" While I understand that using onclick is not the ideal approach, I am employing it because I need to retrieve the product id from the mode ...

issues with jasmine angularjs tests exhibiting erratic outcomes

During the execution of my unit tests, I often encounter a scenario where some random test(s) fail for a specific controller without any apparent reason. The error messages typically look like this: Expected spy exec to have been called with [ Object({}) ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

Experiencing issues with autoungrabify or autolock in cytoscape.js?

I have been working on a web application using Cytoscape.js, and I recently integrated the Edgehandles extension to allow users to add edges. The two types of edges that can be added are undirected and directed. Adding directed edges is functioning as expe ...

Managing file sizes on the client side prior to transferring them to the server side

I am looking to implement client-side validation for file size. The current code only handles success, but I also want to address file size limitations. Right now, if a file exceeds 2MB, it results in a 500 (Internal Server Error) behind the scenes. Is th ...

utilize console.log within the <ErrorMessage> element

Typically, this is the way the <ErrorMessage> tag from Formik is utilized: <ErrorMessage name="email" render={(msg) => ( <Text style={styles.errorText}> ...

increasing the size of a picture without resorting to a pop-up window

Struggling to implement a product details tab within a table that features a clickable image. When the image is clicked, it should enlarge but the width doesn't adjust accordingly. I'm using bootstrap 5.3 and can't seem to identify the root ...

Running res.render in an asynchronous manner within an express application

My goal is to make this router respond asynchronously: var express = require('express'), router = express.Router(); router.get('/', function(req, res, next) { res.render('contact', { titleShown: true, title: & ...

Navigating Time Constraints and Error Management in the World of Facebook Graph API

I'm currently working on a program that involves numerous fql and graph calls, but I'm facing difficulty in handling 'get' or 'post' errors. Can anyone provide guidance on how to implement retry functionality when these errors ...

Keep track of open tabs and their content by utilizing sessions

I am working with Bootstrap Tabs where I have loaded content dynamically using jQuery's load() function. In addition, when a button is clicked, a new tab is generated automatically with a basic HTML form containing various input fields, which is then ...

Assigning a value to a variable can prevent the occurrence of an

My recursive code consists of two pieces aiming to print out half of the array recursively until we reach arrays of length 1. Surprisingly, the code without variable assignment runs infinitely, while the code with variable assignment behaves as expected. ...

Tacking the progress bar onto an array of $.ajax() calls within a Promise.all

FINAL UPDATE 25/06/20: After a thorough investigation, I discovered the root causes of why the progress bar was not functioning as intended. Firstly, dealing with $.ajax() proved to be cumbersome due to its lack of proper promise handling. To resolve this ...

What is the best way to enlarge text size with jquery?

I am attempting to: $('a[data-text="size-bigger"]').click(function () { a=$('span'); b=$('span').css('font-size'); a.css('font-size', b+1); } ); Initially, I ha ...

Tips for executing getJSON requests one after the other

My goal is to showcase a weather forecast for a specific date on my website. Here are excerpts from the code I've used on a trial page that isn't functioning correctly: <script> function displayWeather(date){ $.getJSON(url + apiKey + "/" ...

What is the best way to implement a dropdown menu with JavaScript or jQuery?

I'm looking to create a dynamic dropdown list using Javascript or JQuery that mirrors the functionality of selecting countries, states, and cities. Can someone provide guidance on the best code to achieve this? Below is a snippet of my existing code: ...

"Update your Chart.js to version 3.7.1 to eliminate the vertical scale displaying values on the left

https://i.sstatic.net/7CzRg.png Is there a way to disable the scale with additional marks from 0 to 45000 as shown in the screenshot? I've attempted various solutions, including updating chartjs to the latest version, but I'm specifically intere ...

What could be causing the issue with the JS function that is preventing the button from

I am generating a button dynamically using my JavaScript function and then adding it to the DOM. Below is the code snippet: var button = '<button id="btnStrView" type="button" onclick=' + parent.ExecuteCommand(item.cmdIndex) + ' c ...

The HTML document requests information from a JSP file

I am faced with a situation where I have an HTML page stored on my local computer and a JSP file located on a remote server. My current challenge is: How can I showcase the content from the JSP file on the HTML page? The HTML page is strictly HTML-based ...