Delete row in Google Sheets if certain “word” is found in cell

后端 未结 2 553
我在风中等你
我在风中等你 2021-01-07 09:44

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 som

2条回答
  •  梦谈多话
    2021-01-07 10:37

    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);
    };
    

提交回复
热议问题