Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

google apps script - Two OnEdit functions not working together

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

screenshot

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...