我正在制作一个包含多个工作表标签的大型Google电子表格。当我编辑第6列时,我需要一个时间戳自动输入第1列。我需要在每张工作表中独立完成。这是我到目前为止的脚本,它运行良好。但是,我将添加至少10个标签,我想知道是否有更简单的方法来做到这一点,错误的空间更小。
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "A" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 6 ) { //checks the column
var nextCell = r.offset(0, -5);
if( nextCell.getValue() === '' ) //is empty?
nextCell.setNumberFormat("MM/dd HH:mm:ss")
nextCell.setValue(new Date());
}
}
if( s.getName() == "B" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 6 ) { //checks the column
var nextCell = r.offset(0, -5);
if( nextCell.getValue() === '' ) //is empty?
nextCell.setNumberFormat("MM/dd HH:mm:ss")
nextCell.setValue(new Date());
}
}
if( s.getName() == "C" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 6 ) { //checks the column
var nextCell = r.offset(0, -5);
if( nextCell.getValue() === '' ) //is empty?
nextCell.setNumberFormat("MM/dd HH:mm:ss")
nextCell.setValue(new Date());
}
}
}
答案 0 :(得分:1)
是的,有。只需将所有工作表名称放在一个数组中,然后检查当前编辑的工作表是否在该数组中(使用indexOf)。如果它不在数组中,它将返回-1。在这种情况下,脚本退出。 看看这样的东西是否有效:
function onEdit(e) {
var s = e.source.getActiveSheet(),
sheets = ["A", "B", "C"],
stampCell = e.range.offset(0, -5);
if (sheets.indexOf(s.getName()) == -1 || e.range.columnStart !== 6 || !e.value || stampCell.getValue()) return;
stampCell.setValue(new Date()).setNumberFormat("MM/dd HH:mm:ss")
}