Two OnEdit functions not working together

2019-01-20 17:36发布

问题:

I got two onEdit() function scrips on a Google spreadsheet. But seems like one function is working at a time.

First function is a script to color all Rows, and second one is date function for adding dates on 2 cells based on column edit.

Here are the scripts.

function colorAll() 
{
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 4;
  var endRow = sheet.getLastRow();
  for (var r = startRow; r <= endRow; r++) {
    colorRow(r);
  }
}
SpreadsheetApp.flush();
function colorRow(r)
{
  var sheet = SpreadsheetApp.getActiveSheet();
  var dataRange = sheet.getRange(r, 1, 1, 32);
  var data = dataRange.getValues();
  var row = data[0];
  SpreadsheetApp.flush();
  if(row[14] === ""){
    dataRange.setBackgroundRGB(255, 255, 255);
    dataRange.setFontColor("#000000");
  }
  else if(row[14] === "BEING USED") {
    dataRange.setBackgroundRGB(150, 185, 255);
    dataRange.setFontColor("#004BE1");
  }
}
function onEdit(event)
{
  var r = event.source.getActiveRange().getRowIndex();
  if (r >= 2) {
    colorRow(r);
  }
}

function onOpen(){
  colorAll();

And the second function.

function onEdit(e) {
  var aCell = e.source.getActiveCell(), col = aCell.getColumn(); 
  if(col == 19 || col == 21) {
    var adjacentCell = aCell.offset(0, 1);  
    var newDate = Utilities.formatDate(new Date(), 
      "GMT+1", "dd/MM/yyyy");
    adjacentCell.setValue(newDate);
  }
}

The date function is working but the colorRow function is not, if I remove the date script then the colorRow will work.

Can any one point me in the right direction? Seems like I am missing something

Thanks

回答1:

Barry Smith's comment about "two functions with same name" is right; only the second would execute in that case.

You can have just one spreadsheet-contained function named onEdit(). If you want to use another function as an onEdit trigger, you need to set it up as an installable trigger.

You can use the dialog from Resources -> Current Project's Triggers to install the second trigger.

Alternatively, you could have just one onEdit() simple trigger, but have it call the "sub-trigger" functions, passing the event object e to each of them.

Background: Guide to Triggers.



回答2:

I might be misunderstanding, but it looks like you have two different functions with the exact same name. This can't happen, because the second one is basically overwriting the first one. Give the different names and it should work.