如果我更改单元格,则自动日期

时间:2017-02-13 12:30:39

标签: google-apps-script google-sheets google-spreadsheet-api

我知道这可能是一个简单的功能,但我无法解决它。 我想用以下条件编写一个简单的onEdit函数: 如果连续(3 - xxx)中的任何内容被更改或更新,我想要在特定列中的实际日期。 例如: 如果我更改了单元格B10,我想要单元格G10中的执行日期。也用于单元格E10中的更新。 我的头

function onEdit() {
 var s = SpreadsheetApp.getActiveSheet;
 var range = s.getActiveRange()

我对所有行的循环是:

 for(var i = 1; i<= range.getNumRows() ; i++){
 var r = range.getCell(i, 1)
 if( s.getName() == "Sheet1" ) {

我的if语句:

if( r.getColumn() == 2 ) { 
    var nextCell = r.offset(0, 2);
    if( nextCell.getValue() === '' ) {//is empty?
       var time = new Date();
      time = Utilities.formatDate(time, "GMT+01:00", "HH:mm:ss MM/dd/yy");
       nextCell.setValue(time);
    }
  };
};

如果有人可以帮助我,我会很高兴;-)

2 个答案:

答案 0 :(得分:0)

function onEdit() {

 var s = SpreadsheetApp.getActiveSheet();
 // Instead of getting activeCell we get the whole range
 var range = s.getActiveRange()

 //Use For loop to go through each row and add the time Stamp
 for(var i = 1; i<= range.getNumRows() ; i++){

   var r = range.getCell(i, 1) //Assumption here is that data is pasted in one column only
   // IF that is not always the case, you will have to get the range over which the data was pasted and select column 2

   if( s.getName() == "Gesamt" ) { //checks that we're on the correct sheet
      //var r = s.getActiveCell(); calling it again doesnt change its the value
      // If it is first time keyword added, we will add the current date to "Date Added" Column  
      // We will if it is the first time the "Keyword" column has been written
     for (var c = 1; c<=26; c++){
     if( r.getColumn() == c) {
       var k = 26 - c; //every updated time to the column 26 in the same row
        var nextCell = r.offset(0, k);
        //if( nextCell.getValue() === '' ) {//is empty?
           var time = new Date();
          time = Utilities.formatDate(time, "GMT+01:00", "HH:mm:ss MM/dd/yy");
           nextCell.setValue(time);

      };
    };
   }

 }
}

答案 1 :(得分:0)

没有理由循环编辑触发器,因为每次编辑时你都会自动进入正确的行和列:

function onEdit(e){
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = e.range;  //gets edited range
  var column = range.getColumn();
  if (column < 3){  //stops if column is too low
    return;
  }
  if (column > 6){  //stops is column is too high
    return;
  }

  //else puts date in same row in column G
  var row = range.getRow(); 
  var time = new Date();
  var stringTime = Utilities.formatDate(time, "GMT+01:00", "HH:mm:ss MM/dd/yy");
  sheet.getRange(row, 7).setValue(stringTime);

}