简体   繁体   中英

Google Sheets Script that will adjust (add or remove) rows based on certain conditions

I'm working on a Google Sheet table that is pulling data from another sheet. The table I'm working is using UNIQUE FILTER function so that I can only show a list based on certain conditions. Some conditions require more list thus require more rows and some conditions requires less thus less rows. I want to adjust the number of rows on my table based on these.

I came up with this script to delete blank rows, the problem is that it's only deleting blank rows AFTER the last row that has values. It's not deleting blank rows in between rows with values.

function removeEmptyRows() {
    var ss = SpreadsheetApp.getActive();
    var allsheets = ss.getSheets();
    for (var s in allsheets) {
        var sheet = allsheets[s]
        var maxRows = sheet.getMaxRows();
        var lastRow = sheet.getLastRow();
        if (maxRows - lastRow != 0) {
            sheet.deleteRows(lastRow + 1, maxRows - lastRow);
        }
    }
}

I also cant seem to make a script that will automatically append new rows when a condition results to more data and row requirements.

TLDR;

  1. Need a script that will automatically delete empty rows
  2. Need a script that will automatically add rows and copy top rows formula

Here's a sample sheet I created to better understand what I'm saying: https://docs.google.com/spreadsheets/d/1VU8PsCGcomh3xf3BMI2TUNbnE8UI1RmRpPg4tdrG9Ow/edit?usp=sharing

To delete empty rows inbetween you need to query for all rows either they are empty

A way to do it is to take the first cell (column A) of each row of the data range and define that if A is empty, then the whole rows shall be considered as empty.

Sample:

function removeEmptyRows() {
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();
  for (var s in allsheets) {
    var sheet = allsheets[s];
    var data = sheet.getDataRange().getValues();
    for(var i = data.length; i > 0; i--){
      var maxRows = sheet.getMaxRows();
      var lastRow = sheet.getLastRow();
      if (maxRows - lastRow != 0) {
        sheet.deleteRows(lastRow + 1, maxRows - lastRow);
      }
      var maxRows = sheet.getMaxRows();
      var lastRow = sheet.getLastRow();
      if (data[i-1][0] == "") {
        sheet.deleteRow(i);
      }
    }
  }
}

You need to judge either it is a suitable criterium for you. Maybe in your case the cell in column A might be empty, but the rows has entries in other columns. In this case you need to decide which is the critical column to decide that the whole rows is empty - or test all columns of each row - which would make your code slower.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM