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

  • 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