如何在更新范围时为单元格加时间戳。 (多次)

时间:2016-10-29 08:35:01

标签: google-apps-script google-sheets

我已将此脚本放在我在此处找到的多个答案中,但是,我无法弄清楚如何在同一个活动工作表上多次触发它:

function onEdit(e) {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Goals" )
{
var editRange = { // C4:R31
top : 4,
bottom : 31,
left : 3,
right : 18
};

// Exit if we're out of range
var thisRow = e.range.getRow();
if (thisRow < editRange.top || thisRow > editRange.bottom) return;

var thisCol = e.range.getColumn();
if (thisCol < editRange.left || thisCol > editRange.right) return;

// We're in range; timestamp the edit
var ss = e.range.getSheet();
ss.getRange("D2")   // "D" is column 4
.setValue(new Date()); // Set time of edit in "D2"
}}

我也希望触发以下数据:

function onEdit(e) {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Goals" )
{
var editRange = { // B9:B31
top : 9,
bottom : 31,
left : 2,
right : 2
};

// Exit if we're out of range
var thisRow = e.range.getRow();
if (thisRow < editRange.top || thisRow > editRange.bottom) return;

var thisCol = e.range.getColumn();
if (thisCol < editRange.left || thisCol > editRange.right) return;

// We're in range; timestamp the edit
var ss = e.range.getSheet();
ss.getRange("H2")   // "H" is column 8
.setValue(new Date()); // Set time of edit in "H"
}​}

谢谢, 悦

1 个答案:

答案 0 :(得分:0)

只需取出退货并将两个范围检查移动到相同的编辑中,如下所示:

function onEdit(e) {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Goals" )
{
var editRange = { // C4:R31
top : 4,
bottom : 31,
left : 3,
right : 18
};

// Exit if we're out of range
var thisRow = e.range.getRow();
if (thisRow < editRange.top || thisRow > editRange.bottom) ;

var thisCol = e.range.getColumn();
if (thisCol < editRange.left || thisCol > editRange.right) ;

// We're in range; timestamp the edit
var ss = e.range.getSheet();
ss.getRange("D2")   // "D" is column 4
.setValue(new Date()); // Set time of edit in "D2"

  var editRange = { // B9:B31
  top : 9,
  bottom : 31,
  left : 2,
  right : 2
  }

// Exit if we're out of range
var thisRow = e.range.getRow();
if (thisRow < editRange.top || thisRow > editRange.bottom) ;

var thisCol = e.range.getColumn();
if (thisCol < editRange.left || thisCol > editRange.right);

// We're in range; timestamp the edit
var ss = e.range.getSheet();
ss.getRange("H2")   // "H" is column 8
.setValue(new Date()); // Set time of edit in "H"
}}