Question

I want to copy the content of E6:I6 to the first empty row in the range E13:I17. Then the script should delete the contents of the cells E6 and G6. My code so far looks like this:

function copyAndDelete() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var source = ss.getRange('E6:I6');
  var range1 = ss.getRange('E6');
  var range2 = ss.getRange('G6');
  var l = ss.getDataRange().getValues().length;
  source.copyTo(ss.getRange('E13:I13'), {contentsOnly: true});
  range1.clearContent();
  range2.clearContent();
}

Can anyone help me with this? It would be much appreciated!

Was it helpful?

Solution

try this code:

function copyAndDelete() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var source = ss.getRange('E6:I6');
  var range1 = ss.getRange('E6');
  var range2 = ss.getRange('G6');

  var vals = ss.getRange("E13:I17").getValues();

  var destinationRow = 13;
  for (var i in vals){
    var rowVal = vals[i].join();
    rowVal = rowVal.replace(/,/gm,"");
    Logger.log(rowVal);
    if(rowVal==""){
      destinationRow=13+Number(i);
      ss.getRange("E"+destinationRow+":I"+destinationRow).setValues(source.getValues());
      range1.clearContent();
      range2.clearContent();
      return;
    }
  }
  throw("no empty row found :-(");
}

You didn't specified what to do when there is no empty row in E13:I17, so I decided to throw an error and not perform the copy action in this case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top