Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

events - How can I run a script only when someone adds new rows

Situation:

I have the following script, that runs in OnEdit, but I want to tune this script to run only when someone adds new rows to the sheet.

Script:

function DataValidation2(e)
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  if (s.getName() == "Sheet1"){
  var cell = s.getRange('C3:C');
  var rule = SpreadsheetApp.newDataValidation().setAllowInvalid(false).requireValueInList(['0:15:00', '0:20:00']).build();
  cell.setDataValidation(rule);
  }
}

If possible execute this script only when someone add new row using the boton add include at the end of the sheet?

Best Regards,

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There is a special trigger to detect such changes : onChange

You can even create it programmatically as described in the documentation :

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

and then a function like this that will be called on every change that looks at the number of rows and do something if it changed...and does nothing if the change was something else.

You can add more conditions to handle other cases, for example what to do id rows where deleted

function myFunction(){
  var numRows = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getMaxRows();
  if(ScriptProperties.getProperty('numberOfRows')){
    var nRows = Number(ScriptProperties.getProperty('numberOfRows'));
    if(nRows<numRows){
      //do something because rows have been added in this sheet
      ScriptProperties.setProperty('numberOfRows',numRows);// update value with current value
    }
  }
  ScriptProperties.setProperty('numberOfRows',numRows);// create a start value with current value of simply update if the trigger was called for another reason
}

EDIT following Wchiquito 's comment

here is another (simpler) version that works pretty well too :

function initializeTrigger(){ // run this only once to create a trigger if necessary
  var sheet = SpreadsheetApp.getActive();
 ScriptApp.newTrigger("myFunction")
   .forSpreadsheet(sheet)
   .onChange()
   .create();
}

function myFunction(e){
  Logger.log(e.changeType);
  if(e.changeType=='INSERT_ROW'){
    // do Something
    Browser.msgBox('New row(s) added');
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...