Set value of active cell in Google sheets script

Deadly 提交于 2020-01-14 14:51:28

问题


I want to create a formula which creates a timestamp on a certain cell change. The code below is okay for that. What I want to do now is anchor that timestamp to the sheet by converting the formula to plain text.

If you would do it manually you would select the timestamps, copy them and paste them as values.

I don't want to do it manually so I created the script below. It tries to overwrite the currenct active cell. Does anybody have an idea how to get this working?

Thanks

function cvTimestamp(value) {
  var timezone = "GMT+1";
  var timestamp_format = "dd-MM-yyyy HH:mm:ss"; // Timestamp Format. 


  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];


  var date = Utilities.formatDate(new Date(), timezone, timestamp_format);

  return date

  // Returns the active cell
  var cell = sheet.getActiveCell();
  // try to write date to the active cell as a value.
  cell.setValue(date);

}

回答1:


How about following script? When the name of function is "onEdit()", this is executed. And an edited cell of spreadsheet is changed to "date".

function onEdit(e){
  var row = e.range.getRow();
  var col = e.range.getColumn();
  if (row == 3 && col == 3){ // You can freely define the range for putting DATE. 
    var timezone = "GMT+1";
    var timestamp_format = "dd-MM-yyyy HH:mm:ss";
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    var col = 5; // If you want to put a value to colmun 'E' of editing cell, col is 5.
    var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    ss.getRange(e.range.getRow(), col).setValue(date);
  }
}


来源:https://stackoverflow.com/questions/41889391/set-value-of-active-cell-in-google-sheets-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!