Search code examples
google-apps-scriptgoogle-sheetsdelete-row

Not only auto fill cells but also delete a row when a checkbox is checked


Using a spreadsheet to track issues for a department at work. Currently I have a script built where when you load the issue identifier (column C), column I auto fills with the current date and time to serve as a timestamp to document when the issue was added.

I also want to build a script where when you check the box in column M, the entire row the checkbox is in deletes itself. In other words, when the issue is resolved (complete) you check the box and the entire row containing the issue deletes itself.

Both scripts need to run on all sheets within the workbook.

Here is the script I have written so far, which works perfectly, to add the timestamp:

function onEdit () {
  var s = SpreadsheetApp.getActiveSheet();
  var r = s.getActiveCell();
    
    if( r.getColumn() == 3 ) {
    var nextCell = r.offset(0, 6);
    if( nextCell.getValue() === '' )
      nextCell.setValue(new Date()).setNumberFormat('MM/dd/yyyy HH:mm:ss');
  }
}

Solution

  • SUGGESTION

    In my understanding of your question, you are trying to:

    1. Using an onEdit simple trigger, when a cell in column C gets updated, you are placing a timestamp (which already works).
    2. On the same onEdit trigger, you are also trying to delete the row that is adjacent to a checkbox cell that gets checked on column M.

    You need to use the deleteRow() method to delete a row. Perhaps you can try using this sample tweaked script below using JavaScript Function call() & Conditional (ternary) operator to have a cleaner & organized script flow.

    Sample Script

    function onEdit() {
      var s = SpreadsheetApp.getActiveSheet();
      var r = s.getActiveCell();
      var nextCell = r.offset(0, 6);
    
      const ifColumnC = {
        placeTimeStamp: function () {
          return nextCell.getValue() === '' ? nextCell.setValue(new Date()).setNumberFormat('MM/dd/yyyy HH:mm:ss') : null;
        }
      }
      
      const ifColumnM = {
        deleteRow: function () {
          return r.getValue() == true ? s.deleteRow(r.getRow()) : null;
        }
      }
    
      /**If Column "C" gets edited call "placeTimeStamp" function
       * otherwise if Column "M" checkbox cell gets checked, call the "deleteRow" function
      */
      r.getColumn() == 3 ? ifColumnC.placeTimeStamp.call() :
        r.getColumn() == 13 ? ifColumnM.deleteRow.call() : null;
    
    }
    

    Demo

    enter image description here


    NOTE: If there's anything else missing or have been misunderstood, feel free to comment.