如果单元格为空,则向下读取范围并复制公式

时间:2019-11-30 15:32:44

标签: google-apps-script google-sheets

是Google App脚本的新功能,如果该单元格为空,则尝试编写一个副本以复制公式。我有代码读取范围并返回值。现在,我该如何编写if语句以从公式向下的最后一行复制单元格。我已经附上了代码,日志和电子表格的副本。

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 个答案:

答案 0 :(得分:0)

尝试一下:

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;
}

答案 1 :(得分:0)

您可以将copyTo函数[1]与PASTE_FORMULA参数[2]结合使用,将公式从上一个单元格(向上一行)复制到空单元格中:

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