Search code examples
google-apps-scriptgoogle-sheetstriggersgoogle-forms

Use a trigger to sort a sheet every time a form is submitted


I'm trying to get a Google Sheet to automatically sort when a form is submitted. I have been able to set up the script to sort with the following, but it only works when the spreadsheet is edited manually (not when new data comes in from a form).

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

  var columnToSortBy = 6;
  var tableRange = "A2:F100";

  if(editedCell.getColumn() == columnToSortBy){
  var tableRange = "A2:F100";

 if(editedCell.getColumn() == columnToSortBy){
 var range = sheet.getRange(tableRange);
    range.sort( { column : columnToSortBy } );
  }
}

I need to set up a trigger to make this go when a form is submitted. I found this on Google Developers, but I'm not sure what to use as ("myFunction") in the following:

var sheet = SpreadsheetApp.getActive();
ScriptApp.newTrigger("myFunction")
 .forSpreadsheet(sheet)
.onFormSubmit()
 .create();

Solution

  • Form submission is not an edit, so onEdit trigger is useless here. Instead, use the following simple function with an installable trigger On Form Submission. It's easy to set a trigger manually: in the script editor, go to Resources > Current project's triggers, and add this:

    trigger

    The function:

    function sortSheet() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var columnToSortBy = 6;
      var headers = 1;   // number of header rows, usually 1
      var range = sheet.getRange(headers + 1, 1, sheet.getLastRow() - headers, sheet.getLastColumn());
      range.sort( { column : columnToSortBy } );
    }