Delete a row in Google Spreadsheets if value of cell in said row is 0 or blank

Zack picture Zack · Jun 15, 2012 · Viewed 85.7k times · Source

I'd like to be able to delete an entire row in a Google Spreadsheets if the value entered for say column "C" in that row is 0 or blank. Is there a simple script I could write to accomplish this? Thanks!

Answer

Bryan P picture Bryan P · Nov 16, 2012
function onEdit(e) {
  //Logger.log(JSON.stringify(e)); 
  //{"source":{},"range":{"rowStart":1,"rowEnd":1,"columnEnd":1,"columnStart":1},"value":"1","user":{"email":"","nickname":""},"authMode":{}}
  try {
    var ss = e.source; // Just pull the spreadsheet object from the one already being passed to onEdit
    var s = ss.getActiveSheet();

    // Conditions are by sheet and a single cell in a certain column
    if (s.getName() == 'Sheet1' &&  // change to your own 
        e.range.columnStart == 3 && e.range.columnEnd == 3 &&  // only look at edits happening in col C which is 3
        e.range.rowStart == e.range.rowEnd ) {  // only look at single row edits which will equal a single cell
      checkCellValue(e); 
    }
  } catch (error) { Logger.log(error); }
};

function checkCellValue(e) {
  if ( !e.value || e.value == 0) {  // Delete if value is zero or empty
    e.source.getActiveSheet().deleteRow(e.range.rowStart);
  }
}

This only looks at the value from a single cell edit now and not the values in the whole sheet.