0

I am new to Google Apps Script script writing and trying to self teach by starting off making a generic table. So far I have:

  • made a header;
  • changed the background;
  • changed the font;
  • added data validation;
  • added thick outside borders as well as other borders
  • and keeping a maximum of five rows and columns at any one time

image of the table applying what is listed above

My question is:

How do I remove empty rows in a data range? I have tried multiple methods so far but I like to have the top row as a border so don't want to delete that. This is the script I have written so far

function formatScriptLearning1() {
    var ScriptLearning = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Script learning 1");
    var Header = ScriptLearning.getRange("B2").getDataRegion(SpreadsheetApp.Dimension.COLUMNS);
    var LastRow = ScriptLearning.getLastRow();
    var MaxRows = ScriptLearning.getMaxRows();
    var LastColumn = ScriptLearning.getLastColumn();
    var MaxColumns = ScriptLearning.getMaxColumns();
    var Range = ScriptLearning.getRange(2, 2, LastRow - 1, LastColumn - 1);
    var Outside = Range
    var DataVal = ScriptLearning.getRange(3, 7, LastRow - 1, 1);
    var validation = SpreadsheetApp.newDataValidation().requireValueInList(['Yes', 'No'], true).build();
    var RemainingRows = ScriptLearning.getRange(LastRow + 1, 7, MaxRows);
    var RemainingColumns = ScriptLearning.getRange(2, LastColumn + 1, 1, 5);

    Range.setBorder(true, true, true, true, true, true, null, SpreadsheetApp.BorderStyle.SOLID);
    Outside.setBorder(true, true, true, true, true, null, null, SpreadsheetApp.BorderStyle.SOLID_MEDIUM);
    Header.setBorder(true, true, true, true, true, true, true, SpreadsheetApp.BorderStyle.SOLID_MEDIUM);
    Header.setFontSize(11).setBackground("#ea9999").setFontWeight("Bold").setFontLine("Underline").setFontFamily("Georgia");

    if (MaxRows - LastRow != 0) {
        ScriptLearning.deleteRows(LastRow + 1, MaxRows - LastRow);
    }
    if (MaxColumns - LastColumn != 0) {
        ScriptLearning.deleteColumns(LastColumn + 1, MaxColumns - LastColumn);
    }

    DataVal.setDataValidation(validation);

    ScriptLearning.insertRowsAfter(LastRow, 5);
    ScriptLearning.insertColumnsAfter(LastColumn, 5);
    RemainingRows.clearDataValidations().clearFormat();
    RemainingColumns.clear();

Any help would be greatly appreciated!

Beto Frega
  • 956
  • 6
  • 21

1 Answers1

1
function removeEmptyRows() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const rg=sh.getDataRange();
  const vs=rg.getValues();
  let d=0;
  vs.forEach(function(r,i){if(r.join('').length==0) {sh.deleteRow(i+1-d++);}});
}
Cooper
  • 59,616
  • 6
  • 23
  • 54
  • Thank you! Works grand, just added; ss.insertRowBefore(1).getRange("1:1").clearFormat(); Below that and keeps the border and stuff - really appreciate it @Cooper – Shea Murphy Apr 23 '20 at 08:22