Skip to content

Instantly share code, notes, and snippets.

@dDondero
Created December 8, 2015 19:03
Show Gist options
  • Save dDondero/285f8fd557c07e07af0e to your computer and use it in GitHub Desktop.
Save dDondero/285f8fd557c07e07af0e to your computer and use it in GitHub Desktop.
Google Apps script function to delete rows based on value in cell.
function deleteRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 0;
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
if (row[0] == 'delete' || row[0] == '') { // This searches all cells in columns A (change to row[1] for columns B and so on) and deletes row if cell is empty or has value 'delete'.
sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
rowsDeleted++;
}
}
};
@shifeau
Copy link

shifeau commented Oct 15, 2023

i've been trying to make this condition work for the past hour, and i have used the debugger to see what exactly is stored in each variable (as you can see on the right) and they do match, but the condition is FALSE, and i do not get why.
can someone help? (i have never used google script or javascript before)

image

@joshuadanpeterson
Copy link

This is exactly what I was looking for. Had to finagle it for my own purposes, but I got it to work. I deleted a selection of columns within the target row based on whether the value of a certain cell was less than or equal to a certain number.

const deleteRows = async () => {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const rows = sheet.getDataRange();
  const numRows = rows.getNumRows();
  const values = rows.getValues();

  let rowsCleared = 0; // This should be declared with 'let' to avoid a global variable

  for (let i = 1; i < numRows; i++) {
    // Start from index 1 to skip the header row
    let row = values[i];

    // Check if the value in column E (index 4) is <= 5
    if (row[4] <= 5) {
      // Wrap delete cells in a promise to make it async
      await new Promise((resolve) => {
        // Delete cells from columns A-J in the specific row
        sheet
          .getRange(i + 1, 1, 1, 10)
          .deleteCells(SpreadsheetApp.Dimension.ROWS); // i + 1 to convert index to row number
        resolve();
      });
    }
  }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment