Script deleting all formulas in the Google Sheet, how to fix?

238 Views Asked by At

I have sheet A and B, data from sheet A which matching my criteria I am duplicating on sheet B by using formulas. Since some data not matching my criteria I am getting an empty row.

**PROBLEM STATEMENT **

I have a script which I am planning to use to delete empty rows on the sheet. But I have been notice that its deleting all formulas same time and all formatting.

I need to delete the rows only between the non empty ones. For example row 1,2 have data, row 5 have data, so, only row 3-4 need to be removed, this process should be automatic.

CODE

    function deleteEmptyRows(){ 
          var sh = SpreadsheetApp.getActiveSheet();
          var data = sh.getDataRange().getValues();
          var targetData = new Array();
          for(n=0;n<data.length;++n){
            if(data[n].join().replace(/,/g,'')!=''){ targetData.push(data[n])};
            Logger.log(data[n].join().replace(/,/g,''))
          }
          sh.getDataRange().clear();
          sh.getRange(1,1,targetData.length,targetData[0].length).setValues(targetData);
        }
1

There are 1 best solutions below

9
Yuri Khristich On

I see no sample of your data and have no idea how your sheet looks like, so here is just another guess:

function deleteEmptyRows() {
  const sh = SpreadsheetApp.getActiveSheet();
  const data = sh.getDataRange().getValues();
  const empty_rows = [];
  for (let i in data) if (data[i].join('') == '') empty_rows.push(+i+1);
  empty_rows.reverse().forEach(x => sh.deleteRow(x));
}

Update

The variant of the function that finds for the last row contains visible data and removes all empty (with no visible data) rows above:


function delete_all_empty_rows_above_the_last_filled_row() {
  const sh = SpreadsheetApp.getActiveSheet();

  const data_all = sh.getDataRange().getValues();
  for (var last_row = data_all.length-1; last_row>0; last_row--) {
    if (data_all[last_row].join('') != '') break;
  }
  
  const data = sh.getRange(1,1,last_row+1,3).getValues();
  const empty_rows = [];
  for (let i in data) if (data[i].join('') == '') empty_rows.push(+i+1);
  empty_rows.reverse().forEach(x => sh.deleteRow(x));
}

Update 2

To make the function to file every time as there were changes on the sheet "IF Copy" within the column "A" you need to add something like this:

function onEdit(e) {
  if (e.range.getSheet().getName() != "IF Copy") return;
  if (e.range.columnStart == 1) 
    delete_all_empty_rows_above_the_last_filled_row();
}

But onEdit() trigger works only when you edit sheet manually. If a sheet changes via some formula or another function the trigger doesn't work.