简体   繁体   English

应用程序脚本在对该选项卡进行任何编辑时更新谷歌表格中每个选项卡上的一个单元格中的时间戳

[英]Apps script to update timestamp in one cell on each tab in a google sheet upon any edit of that tab

I have a third party updating a google sheet for me and would like a simple script showing a timestamp in cell B1 of each tab of the script upon any edit of that tab.我有第三方为我更新了谷歌表格,并且想要一个简单的脚本,在对该选项卡进行任何编辑时,在脚本的每个选项卡的单元格 B1 中显示时间戳。 So if Sheet1 was edited in any way, cell B1 of Sheet1 would update the timestamp.因此,如果以任何方式编辑 Sheet1,Sheet1 的单元格 B1 将更新时间戳。 Same with Sheet2.与 Sheet2 相同。 I've got a script that works for Sheet2, but not for Sheet1.我有一个适用于 Sheet2 的脚本,但不适用于 Sheet1。 If I delete the second function, it works for Sheet1.如果我删除第二个函数,它适用于 Sheet1。 I'm sure I'm doing this wrong and would appreciate any help.我确定我做错了,希望能得到任何帮助。 Here's what I have now:这是我现在拥有的:

function onEdit() {
  SpreadsheetApp.getActive().getSheetByName("Sheet1").getRange("B1").setValue(new Date());
}

function onEdit() {
  SpreadsheetApp.getActive().getSheetByName("Sheet2").getRange("B1").setValue(new Date());
}

Are you aware of the fact that an onEdit will always require a manual edit in the spreadsheet?您是否知道 onEdit 始终需要在电子表格中进行手动编辑这一事实? Updates to the sheet by some third party app will not be considered as an edit, hence the timestamp will not be updated.某些第三方应用程序对工作表的更新不会被视为编辑,因此不会更新时间戳。

If you are manually editing the spreadsheet (sheets) you can try如果您手动编辑电子表格(工作表),您可以尝试

function onEdit(e) {
e.source.getActiveSheet().getRange('B1').setValue(new Date());
}

A single Google Apps Script project can't have to onEdit functions due to how JavaScript works.由于 JavaScript 的工作方式,单个 Google Apps 脚本项目不必使用onEdit函数。

The following code example use if statements and the on edit event object to add the timestamp only to the sheet that was edited以下代码示例使用 if 语句和 on edit 事件对象仅将时间戳添加到已编辑的工作表

function onEdit(e) {
  const name = e.range.getSheet().getName();
  if(name === 'Sheet1') e.source.getSheetByName("Sheet1").getRange("B1").setValue(new Date());
  if(name === 'Sheet2') e.source.getSheetByName("Sheet2").getRange("B1").setValue(new Date());
}

Try this:尝试这个:

function onEdit(e) {
  const sh = e.range.getSheet();
  const shts = ["Sheet1","Sheet2"];//Add the sheet names you wish it to work on
  if(~shts.indexOf(sh.getName())) {
    sh.getRange("B1").setValue(new Date());
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM