用于在多张纸上加盖日期戳的脚本

Script for Date Stamping on Multiple Sheets

我对这一切非常非常陌生。我需要帮助,我正在尝试使用脚本编辑器在另一列中输入内容时将日期静态标记在一列中。我想出了如何为一个选项卡执行此操作,但我需要在同一个 sheet 中的多个选项卡上执行此操作,我正在努力让它工作。有没有一种代码适用于此?这是我用于一个选项卡的脚本:

/**
* Creates a Date Stamp if a column is edited.
*/

//CORE VARIABLES
// The column you want to check if something is entered.
var COLUMNTOCHECK = 9;
// Where you want the date time stamp offset from the input location. [row, column]
var DATETIMELOCATION = [0,-8];
// Sheet you are working on
var SHEETNAME = 'Sheet 2'

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  //checks that we're on the correct sheet.
  if( sheet.getSheetName() == SHEETNAME ) { 
    var selectedCell = ss.getActiveCell();
    //checks the column to ensure it is on the one we want to cause the date to appear.
    if( selectedCell.getColumn() == COLUMNTOCHECK) { 
      var dateTimeCell = selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[1]);
      dateTimeCell.setValue(new Date());
      }
  }
}

提前感谢您抽出时间。

要在多个 sheet 上继续该函数,您可以在可接受的名称数组中检查 sheet 名称。

function onEdit() {

    var colToCheck = 9;

    // Offset from the input [row, column]
    var dateOffset = [0, -8];

    // Sheets to proceed on
    var sheetNames = ['Sheet 2', 'Sheet 3'];

    var sheet = SpreadsheetApp.getActive().getActiveSheet();
    var name = sheet.getName();

    if (sheetNames.indexOf(name) > -1) {

      var cell = sheet.getActiveCell();
      var col = cell.getColumn();

      if (col == colToCheck) {

          var dateTimeCell = cell.offset(dateOffset[0], dateOffset[1]);
          dateTimeCell.setValue(new Date());
        }
    }
}

参考资料

Arrays

indexOf()


编辑一个

如果您想要多个选项,可以将它们设置在数组中。数组中元素的顺序必须匹配。

此代码假定时间戳始终位于同一行。

function onEdit() {

    var sheetNames = ['Sheet 2', 'Sheet 3'];
    var colsToCheck = [9, 15];
    var colOffsets = [-8, -4];
    
    var sheet = SpreadsheetApp.getActive().getActiveSheet();
    var name = sheet.getSheetName();
      
    var index = sheetNames.indexOf(name);
    
    if (index > -1) { 
      var cell = sheet.getActiveCell();
      var col = cell.getColumn();
    
      if (col == colsToCheck[index]) { 
          var dateTimeCell = cell.offset(0, colOffsets[index]);
          dateTimeCell.setValue(new Date());
        }
    }
}

编辑两个

对于那些喜欢对象的人

function onEdit() {

    var sheets = {
    
        'Sheet 2': {
            checkCol: 9,
            offset: -8
        },
    
        'Sheet 3': {
            checkCol: 15,
            offset: -4
        }
    };

    var sheet = SpreadsheetApp.getActive().getActiveSheet();
    var name = sheet.getSheetName();
  
    var settings = sheets[name];

    if (settings) { 
      var cell = sheet.getActiveCell();
      var col = cell.getColumn();

      if (col == settings.checkCol) { 
          var dateTimeCell = cell.offset(0, settings.offset);
          dateTimeCell.setValue(new Date());
        }
    }
}