Record changes in another sheet when Google Spreadsheet is edited

Can anyone provide assistance with a problem in Google Spreadsheet?

I am looking to log the name and timestamp when a value in a specific column in the "Venues" sheet is changed. However, I'm having trouble determining if I'm working with the correct spreadsheet or not. I am not very familiar with the class structure of Google API for Spreadsheet. Can someone help me with this?

Here's what I need:

  • Run an event handler when a value in the appropriate column in the "Venues" sheet is changed
  • Retrieve the value from the column with names in this sheet
  • Get the current timestamp
  • Write the name and timestamp to another sheet named "status_history" in the last row (like append)

This is my attempt at writing something, although I know it's not great:

function onEdit(event)
{
  var sheet = event.source.getActiveSheet();

  var cell = sheet.getActiveCell();
  var cellR = cell.getRow();
  var cellC = cell.getColumn();
  var cellValue = cell.getValue();

  var cellCName = cell.getColumn()-1; //column with names
  var name = sheet.getRange(cellR, cellCName).getValue();//get name

  var active_spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  if(sheet.getName() == "Venues"){
    if(cellC == 5 /* if correct collumn was changed */){

      var output_sheet = active_spreadsheet.getSheetByName("status_history");
      var lastRow = output_sheet.getLastRow();
      var lastRange = output_sheet.getRange(lastRow, 1)
      //HERE: write value: name
      var lastRow = output_sheet.getLastRow();
      var lastRange = output_sheet.getRange(lastRow, 2)
      //HERE: write value: time
    }
  }
}

Answer №1

Almost there, just a few adjustments needed.

When working with onEdit functions, it's important to prioritize speed due to frequent invocations.

  • Utilize event information as much as possible to avoid unnecessary calls to Google Apps services.
  • If a service must be used, do so only when absolutely necessary - for instance, wait until after the if statements to determine if you're in the desired cell before calling
    SpreadsheetApp.getActiveSpreadsheet()
    .
  • Exploit the API's capabilities to reduce the number of system calls, such as using appendRow() instead of multiple statements.

After a code inspection, here's the refined function:

function onEdit(event) {
  var sheet = event.range.getSheet();
  if(sheet.getName() == "Venues"){
    // correct sheet
    var cell = event.range;
    //var cellR = cell.getRow();  // not used at this time
    var cellC = cell.getColumn();
    var cellValue = event.value;

    if (cellC == 5) {
      // correct column

      var name = cell.offset(0,-1).getValue(); // get name, 1 column to left
      var time = new Date();                   // timestamp

      var active_spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
      var output_sheet = active_spreadsheet.getSheetByName("status_history");
      output_sheet.appendRow([name,time]);
    }
  }
}

To enhance flexibility and portability, consider using column names for conditional checks. Refer to Adam's answer here for more insights.

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

Storing an ID field across different domains using HTML and JavaScript: Best Practices

Currently, my web app includes a conversion tracking feature that analyzes whether activity "A" by a website visitor leads to action "B." This feature works effectively when the tracking is contained within a single domain but encounters issues across mul ...

Modify div content based on user selection

I have a question about updating the content of a div based on certain conditions in my code. Here is what I'm trying to achieve: <div class="form-control" ns-show="runningImport" disabled="disabled"> {{input[row.header_safe]}}{{select[row. ...

Dealing with all errors across all pages in Angular using a comprehensive error handling approach

I am currently using AngularJS and attempting to capture all errors across all pages. However, I am encountering an issue where it does not catch errors in some instances. For example, when I trigger a ReferenceError in one of the controllers, it is not be ...

Transmit information from a Chrome extension to a Node.js server

Recently, I developed a basic Chrome extension that captures a few clicks on a specific webpage and stores the data in my content_script. Now, I am looking for ways to transmit this data (in JSON format) to my node.js file located at /start. I am seeking ...

I am looking to transfer an image stored in a database onto a card

One issue I am facing is that when trying to display an image from a database, uploaded by a user and showing on a card with additional information like name and price, an icon resembling a paper with green appears in the output. Here's my code snippe ...

Is there a method in JS/jQuery to fill my input field with a constant string and ensure leading zeros are included?

I am looking to create an input textbox that starts with a fixed string followed by up to 6 leading zeros. As the user types in the input box, the leading zeros will be automatically removed once the maximum length of 6 characters is reached. The initial s ...

Ensuring texture consistency for scene backgrounds in three.js

I am facing an issue with adding a background to a scene using a PNG image of 2k resolution. The background appears correctly sized on PC, but on mobile devices, it looks disproportionated. Here is the code snippet I am using: var texture = THREE.ImageUti ...

Jsonip.com is providing both internal and external IP addresses

I'm utilizing to retrieve the IP address of users. In some cases, it is returning both an internal and external IP as a string separated by commas. I am interested in only obtaining the external IP address. Can I assume a specific order for the retur ...

Submit a single data value to two separate models in JSON format using MongoDB

I recently developed a code with 2 essential functions: module.exports.registerAccount = (reqBody) => { let newAccount = new User({ firstName : reqBody.firstName, lastName : reqBody.lastName, email : reqBody.email, mobileNum : reqBody.m ...

Extracting Client's True IP Address using PHP API

Utilizing the following api: I am able to retrieve country, city, and real IP address in localhost (127.0.0.1) successfully. However, when I implement this code on my website, it displays the server's address instead of the client's. How can I r ...

Switch up the position of the vertex shader in Three.js/webgl

I've been working on a particle system using three.js that involves using regular JavaScript loops to change particle positions, but I've found that this method is quite slow. Due to this performance issue, I've decided to delve into transf ...

Adding a personalized service into a separate service within Angular 2

I am having trouble injecting my own service into another service. While I can inject standard Angular services like Http without any issues, attempting to inject custom services results in an exception. For example, here is how MyService is set up: impo ...

What is the best method to determine offsetTop in relation to the parent element instead of the top of

I have a straightforward inquiry: How can one determine the offsetTop of a child element in relation to its parent element rather than the top of the window? The definition of offsetTop indicates that it should give the distance by which a child element i ...

Using Angular routing without relying on a web server to load templates

Can templates be loaded in Angular without a web server? I came across an example here: https://groups.google.com/forum/#!topic/angular/LXzaAWqWEus but it seems to only print the template paths instead of their content. Is there a functioning example of t ...

Guide on creating a menu that remains open continuously through mouse hovering until the user chooses an option from the menu

I have a unique scenario where I am working with two images. When the mouse hovers over each image, two corresponding menu bars appear. However, the issue is that when the mouse moves away from the images, the menu disappears. Any suggestions on how to im ...

I am currently experiencing difficulties with loading files in Magento even though they are present on the server

I am experiencing difficulties with a Magento 1.5.1 installation that was not a fresh setup, but rather one that was transferred to another server (files and database copied over). The issue I am facing is related to the failure of my Javascript files to ...

Confirm Submission Issue in HTML Form

During my testing of the blacklist confirmation dialog, I encountered an issue where clicking the OK button did not submit the form as expected. Instead, it seemed to be stuck in a loop where clicking the button had no effect and the dialog remained on scr ...

I am looking to retrieve a sophisticated/nested JSON data using jQuery

I need some assistance in fetching specific JSON object data. Specifically, I am looking to extract the name, poster image URL, size of the second backdrop image, and version number. As a newcomer to JSON, I was wondering if there is an easy way for me to ...

Submitting Form data to MySQL database with Node.js using Express framework

Currently, I'm working on a server.js file in Node that is intended to send form data from an HTML file to MySQL. However, I seem to be encountering a syntax error with my code. Below, you'll find the code snippet along with the specific error me ...

Is there a way to improve the efficiency of this jQuery function that toggles the image source?

I have implemented a functionality that seems to work, but I'm unsure if it's the most efficient solution. I couldn't find a ready-made 'copy-paste' solution online, so I ended up writing this code myself. I am sticking with the &l ...