Develop a program that executes a function across spreadsheets that satisfy specific conditions

I am currently developing an onEdit(e) script that will highlight cells in a Google spreadsheet (specifically in a certain column) after a specified user has made edits. The challenge I face is ensuring this functionality applies to all spreadsheets with a particular naming convention, as well as all tabs within those spreadsheets that have another specific naming convention. I want to avoid affecting all spreadsheets and tabs indiscriminately.

Here is the code I have so far (partially sourced from Is there a way to automatically highlight changes made in google sheets):

function onEdit(e) {

var sheetsToWatch = ['Template Week'];

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getActiveCell();
var column = cell.getColumn();
var sheetName = sheet.getName();
var matchFound = false;
var user = e.user;
var email = user.getEmail();

if(email == '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c49544d415c4049024f4341">[email protected]</a>' && column == 7)
//if user is Example and editing in Column G - Small Listed Price 
{
  for (var i = 0; i < sheetsToWatch.length; i++) {
      if (sheetName.match(sheetsToWatch[i])) 
      matchFound = true;
  }
}

if (!matchFound) return;
// if not found end

//if found execute color change
var rowColLabel = 
sheet.getRange(cell.getRow(),cell.getColumn()).setBackground('#ff9900');  
  //set backgorund color in orange

}

This implementation functions correctly in my test sheet available at https://docs.google.com/spreadsheets/d/18WVMkkoQViEXXXisXfwTA1ZLY52Zn2ysNa3J8O05MzY/edit?usp=sharing

However, I need it to extend its functionality to any spreadsheet named "Period (Period Number)_YY Theoretical" and to any tab within those spreadsheets named "MMMM-YY". My instinct tells me that using regular expressions to check if the names returned by getActiveSpreadsheet() and getActiveSheet() meet the criteria could populate the 'sheetsToWatch' array, but I am unsure of how to implement this. Any suggestions?

Answer №1

After taking a step back and analyzing the requirements, I simplified my approach to solving this issue. I made adjustments to the onEdit(e) function by removing the (e) trigger and creating two separate functions, spreadsheetName() and sheetNames(). These functions validate the naming conventions of the active spreadsheet and search for matching sheet names respectively. If both conditions are met, the onEdit() function is executed.

I realized that only myself and one other person would be editing these sheets, so I removed the event trigger as it was unnecessary to differentiate between users.

Furthermore, I discovered through API research that duplicating a spreadsheet also duplicates the apps scripts associated with it. This provided me with assurance that all necessary spreadsheets will have the required onEdit() script attached.

This is my final code:

function onEdit() {

var sheetsToWatch = sheetNames();

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getActiveCell();
var sheetName = sheet.getName();
var matchFound = false;

if(cell.getColumn() == 7 && sheetsToWatch != null)
//if user is editing in Column G - Small Listed Price 
{
  for (var i = 0; i < sheetsToWatch.length; i++) {
    if (sheetName.match(sheetsToWatch[i])) { 
    matchFound = true;
    }
  }
}

if (!matchFound) return;
// if no matching sheets found end

//if found execute color change
sheet.getRange(cell.getRow(),cell.getColumn()).setBackground('#ff9900');  
  //set background color to orange
}

Answer №2

onEdit(e) is typically used as a reserved function name for simple triggers in Google Sheets. If you're looking to customize triggers beyond what onEdit(e) can handle, consider using installable triggers with a dedicated Apps Script. By setting up an installable trigger and crafting a script to search through your spreadsheets to add triggers where needed, you can automate this process more efficiently.

To start, it's recommended that you rename your existing onEdit(e) function to avoid potential conflicts or duplicate executions. Separating the simple trigger from the installable trigger will help streamline your automation efforts.

Consider how best to manage your Apps Script quotas, especially regarding execution time limits when dealing with numerous spreadsheets. One approach is to maintain a control panel spreadsheet listing all target spreadsheets and their trigger statuses. Automate the creation of this list if possible, but be cautious of exceeding execution time constraints if handling a large volume of spreadsheets.

Create a script to iterate through the control panel list, adding installable triggers to any spreadsheets lacking them (utilize the status column for tracking) and updating the status accordingly. This systematic approach enhances trigger management and ensures smooth operation across multiple spreadsheets.

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

What is the optimal number of parameters in JavaScript?

After stumbling upon a question on StackOverflow discussing the number of parameters in JavaScript functions (How many parameters are too many?), I started pondering if there is a real limitation on how many parameters a JS function can have. test(65536 ...

Sending a request to a server from my local machine is resulting in a preflight request for 'Access-Control-Allow-Origin'

Encountered complete error: Error message - XMLHttpRequest cannot load . The response to the preflight request does not pass the access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' ...

The property this.props.Values is not defined

I'm facing an issue with a page. Specifically, I am working with the value: this.props.CategoriesList. This value represents a list of categories. The problem is that when I click on a button to navigate to the page where this value is used, it shows ...

AngularJS implemented a header authorization feature

I've been attempting to include an authorization header in my requests, but I'm facing some issues. Here is the code I am using: var config = {headers: { 'Authorization': token } }; return $http.get('http://localhost:3000/api ...

An effective method to showcase the HTML content retrieved by getElementsByClassName using JSON.parse()

Can someone help me modify this code so that it displays the value of favFood? It currently works with getElementById but not getElementsByClassName, and I want to use a class: server file - ProcesssingFileOnServer.php: <?php $myObj = new stdClass(); ...

Tips for modifying the color of a query term in HTML

Within my HTML file, I have <p class = "result"> {{searchResult}} </p> where {{searchResult}} represents the result of a search term. If I search for the term "hot", {{searchResult}} would display a string containing the word "hot" in a ...

Display the outline of a translucent image

Looking to create an image reveal effect on my website. I want to display only the outline of a transparent image using brightness, then gradually reveal the full image by removing the brightness effect. Currently, I achieve this with a black outline usi ...

Issue: Failed to locate module @angular/core

When attempting to run an Angular 4 application, I consistently encounter the following error: ERROR in Could not resolve module @angular/core There are no additional errors present. There are no dependency issues whatsoever as @angular/core is located i ...

Issue detected: data exceeds limits (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7) within next-js and ethereum

While working on my Ethereum and Next.js project, I encountered an error during the initialization of the project: Error: data out-of-bounds (length=3, offset=32, code=BUFFER_OVERRUN, version=abi/5.0.7) at Logger.makeError (/home/Documents/projects/eth ...

Using Bootstrap multiselect, you can easily control the display of a second menu based on the selection in the first menu

On my website, I am working with two menus. When I select Abon from the first menu, it should display all li elements under the Abon optgroup (Abon-1, Abon-2). If I uncheck block in the second menu, those elements should disappear. The code consists of Sel ...

Issue with Vuetifyjs theme variable failing to function properly in version 1.0.0

Check out the step-by-step instructions provided in https://vuetifyjs.com/en/style/theme. I successfully changed the theme using the code below with vuetifyjs version 0.13.0. However, after updating to vuetifyjs 1.0.5, the font still displays correctly bu ...

My function invocations seem to be malfunctioning

Originally, I wrote code without using functions to prototype and it worked perfectly fine: $(function() { $(".PortfolioFade img") .mouseover(function() { popup('PORTFOLIO'); var src = $(this).attr("src").rep ...

Warning message in React about missing floating prop in components

application.js (Webpack Entry Point) import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; document.addEventListener('DOMContentLoaded', () => { ReactDOM.render(<App /> ...

My picture is refusing to load... Why does it keep saying "image not found"? Any thoughts on why this might be

I've been trying to display a picture of myself on my html canvas, the image is stored in the correct folder. However, I keep encountering a strange error (shown above) and I can't seem to figure out what's causing it. If you have any insigh ...

Uploading a file with AngularJS and storing it in a database

I have been attempting to implement ngFileUpload in order to upload images and store them in a database – specifically, a mongoLab database that accepts JSON objects which can be posted using this syntax: $http.post('myMongoName/myDb/myCollection/ ...

Using v-select to bind values directly to objects

My v-select is set up to map objects in the following way: <v-select v-model="object" :items="objectsArray" label="Select Object" item-text="name" item-value="id" ></v-select> Where: The 'object ...

Bidirectional Data Flow with rxjs in Angular

After adapting an Angular template and component from Angular Material's dashboard schematic, I wanted to manipulate the properties on the "cards" object using events and two-way data binding. Initially, it seemed like two-way data binding was working ...

Unexpected token . encountered in Javascript: Uncaught Syntax Error. This error message is triggered when

As someone who is completely new to programming, I was given the task of creating a voting website for a class assignment. In order to store data locally, I managed to create variables and implement them using local storage: var eventName = document.getEl ...

What is the best way to enable editing of a form when the edit button is clicked?

I have created a simple profile page where users can edit their profile information. I have placed a button at the end of the page. Initially, the form should be uneditable, but when the button is clicked, the form becomes editable. I attempted to use `dis ...

Using JQuery validate to extract the interest rate from a regular expression

I am looking for a regular expression that can extract the interest rate. I need it to accept values such as: Examples: 0 0.4 0.44 4 44 4.00 44.00 4.2 4.22 44.22 Minimum value allowed is 0 and maximum is 99.99 The regular expression should be ab ...