Add timestamp to named column in Google Spreadsheet onEdit script

后端 未结 2 760
半阙折子戏
半阙折子戏 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);
      }
    }
    
    0 讨论(0)
  • 2020-12-11 08:07

    This was easier than I thought! Between the last 2 brackets:

    var dateCol = headers[0].indexOf('Updated By');
    
      if (dateCol > -1 && index > 1) { // only timestamp if 'Updated By' header exists, but not in the header row itself!
        var cell = sheet.getRange(index, dateCol + 1);
        var Who = Session.getActiveUser();
        cell.setValue(Who);
      }
    
    0 讨论(0)
提交回复
热议问题