google-sheetsgoogle-apps-scripttriggerstimestamp

How to Run Script on Multiple Spreadsheet Tabs


I am writing this to understand how to run a script on multiple tabs (worksheets) in one google spreadsheet file.

  1. What I am trying to do with the script:
  1. Background of all tabs in the spreadsheet:
  1. Problem that I am having:

    • Only the last script would work right after I save it.

    step1: write down code for tab Apple and save, script will work on Apple.

    step2: write down code for tab Banana (in the same script file, right after code for Apple) and save, script will work on Banana, but not working on Apple anymore.

  2. What I have tried so far (not working):

  1. Code that I am using:
    function onEdit(e) {
      addTimestamp(e);
    }
    
    function addTimestamp(e){
      var startRow = 2;
      var targetColumn = 24;
      var ws = "Apple";
    
      var row = e.range.getRow();
      var col = e.range.getColumn();
    
      if(col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws){
    
        var time = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'yyyy/MM/dd');
    
        e.source.getActiveSheet().getRange(row,25).setValue(time);  
        }
    }
    
    function addTimestamp(e){
      var startRow = 2;
      var targetColumn = 66; 
      var ws = "Banana"; 
    
      var row = e.range.getRow();
      var col = e.range.getColumn();
    
      if(col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws){
    
        var time = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'yyyy/MM/dd');
    
        e.source.getActiveSheet().getRange(row,67).setValue(time);
        }
    } 
    

Solution

  • Code snippet:

    Considering the previous points, your code could be greatly simplified:

    function addTimestamp(e) {
      const range = e.range;
      const sheet = range.getSheet();
      const statusColumn = sheet.getRange("1:1").getValues()[0]
                                .findIndex(header => header === "status") + 1;
      if (range.getColumn() === statusColumn && range.getRow() > 1) {
        const time = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'yyyy/MM/dd');
        range.offset(0,1).setValue(time);
      }
    }
    

    Update:

    If you want to find the timestamp column by header name too, just replace this:

    range.offset(0,1).setValue(time);
    

    With this:

    const timestampColumn = sheet.getRange("1:1").getValues()[0]
                                 .findIndex(header => header === "timestamp") + 1;
    sheet.getRange(range.getRow(), timestampColumn).setValue(time);