在我的 Google 工作表文档中,目前有 4 个定期更新的单元格。每次更新这些时,我想为一个单独的单元格添加时间戳。
我可以让附加的脚本适用于 1 个单元格,但是当我复制该脚本以使其适用于另一个单元格时,它会停止前一个单元格的工作。
function onEdit(event)
{
var timezone = "GMT+1";
var timestamp_format = "dd-MM-yyyy hh:mm:ss";
var updateColName = "Development Team Comments";
var timeStampColName = "To update select cell";
var sheet = event.source.getSheetByName('WIP');
var actRng = event.source.getActiveRange();
var editColumn = actRng.getColumn();
var index = actRng.getRowIndex();
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var dateCol = headers[0].indexOf(timeStampColName);
var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
if (dateCol > -1 && index > 1 && editColumn == updateCol) {
var cell = sheet.getRange(index, dateCol + 1);
var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
cell.setValue(date);
}
}
我也尝试过此代码,但它似乎不适用于后续单元格:
function onEdit(event)
{
var timezone = "GMT+1";
var timestamp_format = "dd-MM-yyyy hh:mm:ss"; // Timestamp Format.
var updateColName = "Development Team Comments";
var timeStampColName = "To update select cell";
var sheet = event.source.getSheetByName('WIP'); //Name of the sheet where you want to run this script.
var responseArray = ["o update select cell", "Bupa time stamp","Date Stamp Move Live"];
var questionArray = ["Development Team Comments", "BDC proofing comments", "Approved Y"];
var actRng = event.source.getActiveRange();
var editColumn = actRng.getColumn();
var index = actRng.getRowIndex();
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var dateCol = headers[0].indexOf(timeStampColName);
var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
var cell = sheet.getRange(index, dateCol + 1);
var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
cell.setValue(date);
}
}
我期望我应该能够做的是能够更新任何单元格并让它们像上面的脚本一样显示当前时间。我需要复制这个还是有办法插入单元格引用。
最佳答案
看起来您的脚本对于您实际需要的内容来说相当复杂,它正在检查所有 header 等,而实际上您需要的只是一些基于 if
的 setValue()
> 语句,将其放入 onEdit(e)
触发器中即可完成!
function onEdit(e) {
var sheet = e.source.getSheetByName('WIP');
var timezone = 'GMT+1';
var format = 'dd-MM-yyyy hh:mm:ss';
var cell = e.range;
var row = cell.getRow();
var col = cell.getColumn();
var stamp = Utilities.formatDate(new Date(), timezone, format);
if (col === 1) { //if edited cell is in column A
sheet.getRange(row, 4).setValue(stamp); //set timestamp in column D
}
if (col === 2) { //if edited cell is in column B
sheet.getRange(row, 5).setValue(stamp); //set timestamp in column E
}
if (col === 3) { //if edited cell is in column C
sheet.getRange(row, 6).setValue(stamp); //set timestamp in column F
}
}
此脚本将运行到 C 列,如果您想添加更多内容,只需调整 if
语句和 getRange()
中的数字以满足您的要求.
关于javascript - 如何在 Google 表格上为多个单元格添加时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56291154/