结合这两个脚本

时间:2019-09-25 18:30:26

标签: google-apps-script

我试图结合两个脚本来同时运行,但无法同时运行它们。以下是两个单独的脚本。

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

  var columnToSortBy = 7;
  var tableRange = "A2:T399"; // What to sort.

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

function onEdit(event)
{ 
  var timezone = "GMT-5";
  var timestamp_format = "MM-dd-yyyy"; // Timestamp Format. 
  var updateColName = "Parent Sign-Out";
  var timeStampColName = "Timestamp";
  var sheet = event.source.getSheetByName('Area Check-in'); //Name of the sheet where you want to 
run this script.


  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' 
header exists, but not in the header row itself!
var cell = sheet.getRange(index, dateCol + 1);
var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
cell.setValue(date);
  }
}

我不确定是否需要分别命名。如果是这样,我将如何添加名称?

1 个答案:

答案 0 :(得分:4)

function onEdit(e) {
  var sh=e.range.getSheet();
  if(sh.getName()=='NameOfSheetYouWantThisToWorkOn') {
    if(e.range.columnStart==7) {   
      e.range.getSheet().getRange("A2:T399").sort({column:7,ascending:false});
    }
  }
  if(sh.getName()=='Area Check-in') {
    var headers=sh.getRange(1,1,1,sh.getLastColumn()).getValues()[0];
    var dateCol=headers.indexOf("Timestamp")+1;
    var updateCol=headers.indexOf("Parent Sign-Out")+1;
    if (dateCol>0 && e.range.rowStart>1 && e.range.columnStart == updateCol) {
      sh.getRange(e.range.rowStart,dateCol).setValue(Utilities.formatDate(new Date(), "GMT-5", "MM-dd-yyyy"));
    }
  }
}