Skip to content Skip to sidebar Skip to footer

Delete Row In Google Sheets If Certain "word" Is Found In Cell

I have a Google Sheet with over 3000 rows. Some of the rows contain words that are not relevant..So I need a way to delete these in bulk. For example, cells will contain something

Solution 1:

Using the indexOf trick, I've managed to get the desired effect by changing...

This:

    if (row[1] =='old')

To This:

    if (row[1].indexOf("old") >-1)

What's happening here:

The 'indexOf' goes in and finds the position of the first occurrence of the word "old", then returns back a number length value. If it doesn't find the word, the result will be -1. So, as long as you specify greater than "> -1", it will be true..and you'll be good!

Here's the complete code if anyone else needs this in the future,

/**
 * Deletes rows in the active spreadsheet that contain 'word' in column B
 * For more information on using the Spreadsheet API, see
 * https://developers.google.com/apps-script/service_spreadsheet
 */function readRows() {
 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[1].indexOf("old") > -1) {
 sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
 rowsDeleted++;
 }

 }
};


/**
 * Adds a custom menu to the active spreadsheet, containing a single menu item
 * for invoking the readRows() function specified above.
 * The onOpen() function, when defined, is automatically invoked whenever the
 * spreadsheet is opened.
 * For more information on using the Spreadsheet API, see
 * https://developers.google.com/apps-script/service_spreadsheet
 */function onOpen() {
 var sheet = SpreadsheetApp.getActiveSpreadsheet();
 var entries = [{
 name : "Remove rows where column B is 'old'",
 functionName : "readRows"
 }];
 sheet.addMenu("Remove Rows", entries);
};

Solution 2:

   function deleteRows() {
  varsheet= SpreadsheetApp.getActiveSheet();
  varrows= sheet.getDataRange();
  varnumRows= rows.getNumRows();
  varvalues= rows.getValues();

  vartoDelete= [];

varre=newRegExp('old','gi'); 
  for (varrow=0; row < values.length; row++) { 
  for(varcolumn=0;column<values[row].length;column++){ 
  if (re.exec(values[row][column])){
  toDelete.push(row); } } }


  for(vardeleteRow= toDelete.length-1; deleteRow >= 0;deleteRow--){
    sheet.deleteRow(toDelete[deleteRow]+1);
  }

  SpreadsheetApp.flush();
};

Post a Comment for "Delete Row In Google Sheets If Certain "word" Is Found In Cell"