Search code examples
google-sheetsgoogle-sheets-querygoogle-apps-script-editor

Newbie: writing a script for google sheets that will run on all sheets


I am a real novice at this (not even). Have never written code in my life-just copied the following code off a website that explained how to do it. I a google doc that I need to be sorted according to Column C continuously as new data is added. This is the code I was given:

function onEdit() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange(3, 1, sheet.getLastRow() - 2, sheet.getLastColumn());
  range.sort({column: 3, ascending: true});
}

It works partially, but I need it to be applied to all sheets/tabs in the document. Thanks in advance!


Solution

    • Your code includes the line var sheet = SpreadsheetApp.getActiveSheet(); and the rest of you code is based on sheet - so it run only on one sheet, the one that is active when new data is inserted, so the one in which the edit is performed
    • If instead you want to perform the sorting on each edit in all sheets of the spreadsheet, you need the method getSheets() to retrieve all sheets of the spreadsheet as an array
    • Subsequently you need to loop through the array to apply the sorting function to each sheet

    Sample:

    function onEdit() {
      var sheets = SpreadsheetApp.getActive().getSheets();
      for (var i = 0; i < sheets.length; i++){
        var sheet = sheets[i];
        var range = sheet.getRange(3, 1, sheet.getLastRow() - 2, sheet.getLastColumn());
        range.sort({column: 3, ascending: true});
      }
    }
    

    Important:

    The onEdit trigger only detects human-made edits like typing of text. If instead you want to fire the trigger on changing the document structure, such as e.g. inserting a new empty row (which is different from typing values into cells of an alreday existing empty row), you would need to replace the onEdit trigger, through the installable onChange trigger, see also here