Add timestamp to named column in Google Spreadsheet onEdit script

后端 未结 2 764
半阙折子戏
半阙折子戏 2020-12-11 07:48

I\'m trying to figure out how to retrieve the index of a column with a specific name in a Google Spreadsheet script.

I\'m working on a custom Google Script that auto

2条回答
  •  被撕碎了的回忆
    2020-12-11 08:04

    You could get the values in your header row, and search for the required header in those values using indexOf().

    function onEdit(event)
    { 
      var timezone = "GMT-4";
      var timestamp_format = "yyyy-MM-dd HH:mm:ss";
      var sheet = event.source.getActiveSheet();
    
      // note: actRng = the cell being updated
      var actRng = event.source.getActiveRange();
      var index = actRng.getRowIndex();
    
      var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
      var dateCol = headers[0].indexOf('Last Updated');
    
      if (dateCol > -1 && index > 1) { // 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);
      }
    }
    

提交回复
热议问题