1
votes

New to Google App Script and trying to write a copy to copy down a formula if the cell is empty. I have code to read the range and return the values. Now how do I write the if statement to copy the cell from the last row with the formula down. I have attached copies of the code, logs, and spreadsheet.

function copytime() {
 var activesheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Schedule");
 var lr=activesheet.getLastRow()-1;
 var rangestart=activesheet.getRange(2,10,lr,5)
 var values=rangestart.getValues();

  for (var row in values){
    for (var col in values[row]){
      var rowempty=values[row][col];
    Logger.log(rowempty);
//      if rowempty==""



  }
 }
}

enter image description here

2
Welcome to StackOverFlow please take this opportunity to take the tour and learn how to How to Ask, format code and minimal reproducible example. - Cooper

2 Answers

0
votes

Try this:

function clearFormulaIfNotEmpty() {
 var sh=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Schedule");
 var rg=sh.getRange(2,10,sh.getLastRow()-1,5)
 var v=rg.getValues();
 var f=rg.getFormulas();
  for(var i=0;i<v.length;i++) {
    for (var j=0;j<v[i].length;j++) {
      if(v[i][j]) {
        f[i][j]='';
      }
    }
  }
  return f;
}
0
votes

You can use copyTo function [1] with PASTE_FORMULA parameter [2] to copy the formulas to the empty cells from the immediately above cell (one row up):

function copytime() {
  var activesheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Schedule");
  var lr = activesheet.getLastRow()-1;
  var rangestart = activesheet.getRange(2,10,lr,5);
  var values = rangestart.getValues();

  for (var row in values){
    for (var col in values[row]){
      var rowempty = values[row][col];

      if (rowempty == "") {
        var formula = activesheet.getRange(1+Number(row), 10+Number(col));
        var cell = activesheet.getRange(2+Number(row), 10+Number(col));
        formula.copyTo(cell, SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
      }    
    }
  }
}

[1] https://developers.google.com/apps-script/reference/spreadsheet/range#copyTo(Range,CopyPasteType,Boolean)

[2] https://developers.google.com/apps-script/reference/spreadsheet/copy-paste-type.html