What is the reason that this Google apps script can only function properly when I manually input the range?

Is there a way to keep certain sheets in a Google Doc continuously sorted by the first column, which contains timestamps? Although I have a script that works when I hard-code the range, it doesn't seem to function properly when using getLastRow() and getLastColumn() to define the range. The code snippet below shows my attempt, but uncommenting it causes the code to fail. Any ideas on what might be causing this issue?

  var sheet = event.source.getActiveSheet();
  var editedCell = sheet.getActiveCell();
  var columnToSortBy = 1;
  var tableRange = "A2:Z99";
  if(editedCell.getColumn() == columnToSortBy && /^Form\sResponses/.test(sheet.getSheetName())){  
    var range = sheet.getRange(tableRange);
    /* WHY DOESN'T THIS WORK -- var range = sheet.getRange(2,1,sheet.getLastRow(), 
sheet.getLastColumn()-1); */
    range.sort({column: columnToSortBy , ascending:false});
  };
};

Answer №1

Method:

To determine the position of the last column and row with content, you can utilize the functions .getLastColumn() and .getLastRow(). These positions can then be used to dynamically create your desired range using

.getRange(row, column, numRows, numColumns)
.

If your goal is to define the range "A2:Z99", this translates to:

.getRange(2,1,sheet.getLastRow()-1, sheet.getLastColumn())
;

Resolution:

var sheet = event.source.getActiveSheet();
var editedCell = sheet.getActiveCell();
var columnToSortBy = 1;
//var tableRange = "A2:Z99";
if(editedCell.getColumn() == columnToSortBy && /^Form\sResponses/.test(sheet.getSheetName())){  
   //var range = sheet.getRange(tableRange);
   var range = sheet.getRange(2,1,sheet.getLastRow()-1, sheet.getLastColumn()); // A2:Z99
   range.sort( { column : columnToSortBy , ascending:false});
}; 

Sources:

Sheet getRange(row, column, numrows, numcloumns)

Sheet getLastRow()

Sheet getLastColumn()

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

Add some text onto the Box Component in Material UI

I am looking to replicate the hover functionality (UI) seen in this example: Desired UI Source: Since adjusting background image styles can be complex, I have opted to use the Box Component from Material UI. Within the Box Component, I have implemented th ...

Tips for resolving issues with the carousel container in bootstrap?

Is there a way to adjust the carousel box container in Bootstrap so that it remains consistent even with images of varying sizes? Currently, the box size changes based on the image dimensions when sliding through the carousel. Sample Code: <h1>Caro ...

Consistently receiving the identical result even when the checkbox remains unselected

Displaying a Checkbox Input <input id="idCheckbox" name="check" type="checkbox" value="AllValue" style="width: auto; height: auto; font-weight: bolder;" data-bind="checked: idCheckbox" /> The checkbox input will always have the value "AllValue ...

The req.body in Express.js appears to be empty when utilizing form-data

snapshot of postman When I send data using form-data in my Express.js application, req.body appears to be empty. However, if I send the data using raw JSON, the expected object is present in req.body. Below is how my setup looks: Here is my index.js file ...

The SQL query fails to execute when triggered by window.location.href

Whenever a selection is made, I trigger a Javascript code using the onchange function. I pass along 2 parameters: //capaciteit.php function testfunction(week, id) { window.location.href = "capaciteitberekening.php?week=" + week + "&id=" + id; } The f ...

What are the recommended steps for making an AJAX request to execute C code smoothly?

I am currently working on designing a web interface for a device that is powered by an underlying C application and involves intensive hardware operations. The primary function of the web interface is to display status information to the user. Specifically ...

Tips for properly sending a JWT token

When working on my angular application, I encountered an issue while trying to send a jwt token as a header for request authorization. The error 500 was triggered due to the jwt token being sent in an incorrect format. Here is how I am currently sending it ...

Controlling the window opener; Inserting text into an element in the parent window

A pop-up window allows users to select files, then displays the selected image's URL. However, I need to take additional steps beyond that. I am seeking a method to input the URL into an input element on the parent window. window.opener.document.wri ...

leveraging the default browser behavior for the href and target attributes within an <a> element in Angular 2

How can the behavior of a simple anchor tag in Angular 2 be implemented without being overridden by the routing module? <a href="some url" target="_whatever"> It is crucial to prevent the routing module from highjacking the URL using the base href. ...

Tips for preloading a script in nextjs

I'm having trouble incorporating a script into my website. The issue is that the script doesn't load properly the first time the page loads, but after a few refreshes, it works and the responsible iFrame shows up. I've attempted several di ...

What is the method for verifying a condition within a Javascript function?

Recently delving into Javascript, I have encountered a situation with a JS method. It seems that most of the time, both the SSID and SecurityMode are the same in the lists of wifi networks I receive. I would like to filter out instances where both SSID and ...

Can someone explain why my Laravel route is consistently showing a 404 error?

Currently, I am attempting to perform an AJAX request for a form post type. However, the PHP parse script I am trying to send the data to is returning a 404 error as observed through Chrome developer tools. Below is the code snippet: <script type="text ...

Unable to fetch a new session from the selenium server due to an error

I'm currently in the process of setting up Nightwatch.js for the very first time. I am following the tutorial provided at this link: https://github.com/dwyl/learn-nightwatch Unfortunately, I have encountered a barrier and require assistance to resolv ...

Hide popup in React Semantic UI when clicking on a different popup

I've integrated React Semantic UI into my application and I'm using the semantic Popup component to display tooltips. One issue I'm encountering is that when I click on a popup button, previously opened popups are not automatically closing. ...

Is there a way to order the execution of two functions that each produce promises?

With my code, I first check the status of word.statusId to see if it's dirty. If it is, I update the word and then proceed to update wordForms. If it's clean, I simply update wordForms. I'm looking for advice on whether this is the correct a ...

The button is not displaying

When trying to click on the "Open device Access" button within the accordion, it does not appear. It seems like there may be an issue with the JavaScript as the transition from "display none" to "display block" is not functioning properly. The "Open device ...

The React application is showing an empty page without any visible errors during the compilation process

I'm having trouble with my React app - it compiles without errors but only shows a blank page. Can someone help me figure out what's wrong with my code? I'm new to React and could use some guidance. index.js import React from 'react&ap ...

Tips for moving an element to the end of an array

Patients' data is stored in the MongoDB database, and all patients are mapped through on the frontend to display a list. An additional boolean value indicates whether a patient is archived or not. If a patient is archived, it should be displayed at th ...

Managing Multiple File Inputs in React Using useRef Array Results in an Undefined Value

In the process of developing a React application, I encountered an issue where multiple file input elements were dynamically rendered using the Swiper component and Dropzone. However, upon attempting to retrieve all the selected files from these inputs dur ...

Having trouble configuring CORS in Sails.js for fetching Google Maps geolocation data?

Struggling to enable CORS in my local app, I've been following the sails.js documentation which suggests changing the setting "allRoutes: true" for enabling cors. However, when attempting to access the Google API using Angular: getLocation: function( ...