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

前端 未结 10 788
情书的邮戳
情书的邮戳 2020-11-29 02:01

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 w

10条回答
  •  [愿得一人]
    2020-11-29 02:52

    I wrote this script to do the same thing for one of my Google spreadsheets. I wanted to be able to run the script after all the data was in the spreadsheet so I have the script adding a menu option to run the script.

    /**
     * Deletes rows in the active spreadsheet that contain 0 or
     * a blank valuein column "C". 
     * 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[2] == 0 || row[2] == '') {
          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 C is 0 or blank",
        functionName : "readRows"
      }];
      sheet.addMenu("Script Center Menu", entries);
    };
    

    Test spreadsheet before:

    enter image description here

    Running script from menu:

    enter image description here

    After running script:

    enter image description here

提交回复
热议问题