我正在与多个用户协作制作一个电子表格。电子表格管理员要求我为任何新的/更改的条目创建一个时间戳;因此,我无法保护范围以防止任何人篡改时间戳列。请注意,用户将不断添加/删除行(包括在标题上方添加行)和列,因此“时间戳”列始终在变化。今天“时间戳”列位于单元格 E2 中,但明天它可能会更改为单元格 C4。
下面是我尝试的代码,我尝试循环每个单元格,直到找到“时间戳”,以便我可以获得行号和列号。但我的我的代码有问题。
function onEdit(e){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getActiveSheet();
var tf = thisSheet.createTextFinder("timestamp");
// This finds Row # where cell = "timestamp"
var thisRow = tf.findNext().getRow();
// This is supposed to find Col # where it = "timestamp" but I'm having issues
var thisCol = tf.findNext().getColumn();
var ss = e.source;
var main_sheet = ss.getSheetByName('sports_team');
const row = e.range.getRow();
if (e.source.getActiveSheet().getName() === "sports_team") {
const currentDate = new Date();
main_sheet.getRange(thisRow, thisCol).setValue(currentDate);
}
}
getCurrentMatch()
查找列索引查找行索引后再次调用
findNext()
函数预计会返回空值,除非工作表中存在另一个值为“timestamp”的单元格。要在查找行索引后获取列索引,我建议使用 getCurrentMatch()
代替。
我对您的代码进行了一些修改,使其在编辑工作表时自动在时间戳列上添加日期。试试这个:
function onEdit(e){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("sports_team");
var tf = thisSheet.createTextFinder("timestamp");
// This finds Row # where cell = "timestamp"
var thisRow = tf.findNext().getRowIndex();
// I used getCurrentMatch() to find the column index instead of findNext()
var thisCol = tf.getCurrentMatch().getColumnIndex();
//Finds the current active sheet
var main_sheet = e.source.getActiveSheet();
//Finds the index of the row being edited
var row = e.range.rowStart;
if (main_sheet.getName() == "sports_team" && row > thisRow) {
const currentDate = new Date();
//Inserts the date on the row being edited, under the timestamp column
main_sheet.getRange(row, thisCol).setValue(currentDate);
}
}
请注意,如果正在编辑的单元格/行位于时间戳标题下方,则此代码仅在时间戳列上插入日期。
我宁愿不假思索地修改代码,而没有真正考虑太多。但现在我不明白在将内容更改为 new Date() 后如何找到时间戳单元格?
function onEdit(e) {
var sh = e.range.getSheet();
if (sh.getName() == "sports_team") {
const mc = sh.createTextFinder("timestamp").getCurrentMatch()
if(mc) {
const r = mc.getRow();
const c = mc.getColumn();
}
sh.getRange(r, c).setNote(new Date());//I put the timestamp in the note
}
}
正如您在该表中所做的那样,我可能更喜欢将时间戳存储在 PropertiesService 或 ascii 文件中。
onEdit 触发器和函数的一个大问题是它非常慢,而且听起来好像有一群用户并不真正关心。可能无法满足电子表格管理员的要求。