将谷歌应用程序脚本功能应用于单元格范围

时间:2016-01-20 06:25:09

标签: google-apps-script google-sheets

我有一个功能,用值替换已解决的公式,而不是解决公式只是刷新。但是我需要这个功能将它应用于几张纸上的固定范围(B2:G)细胞。请帮忙解决一下,或者只是说找出更好的搜索答案?

function testfindfunc1() 
{
  var ss1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('18869')
  var targetrow = 37;
  var targetcell = 2;
  var result = ss1.getRange(targetrow, targetcell);
  //var formula1 = result.getFormula();
  var findVal = ss1.getRange(targetrow, targetcell).getValue();

  if( findVal == ('#N/A') || findVal == ('Loading...')) 
  {
   var rangeToCopy = ss1.getRange(targetrow, targetcell);
   rangeToCopy.copyTo(ss1.getRange(targetrow, targetcell));
  } 
  else 
  {
   result.setValue(findVal);
  }
}

1 个答案:

答案 0 :(得分:3)

在单元格上设置值将删除其上的公式。首先选择所需的loop,然后选择function testfindfunc1() { var ss1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('18869'); var range = ss1.getRange('B2:G10'); var numRows = range.getNumRows(); var numCols = range.getNumColumns(); for (var i = 1; i <= numRows; i++) { for (var j = 1; j <= numCols; j++) { var currentValue = range.getCell(i,j).getValue(); if( currentValue == "#N/A"|| currentValue == "Loading...") { // if formula has not exicuted // do nothing, leave the cell as it is } else { //remove the formula and set the value range.getCell(i,j).setValue(currentValue); } } } } ,检查每个单元格的范围是否已执行公式。

function testfindfunc2() 
{
  var ss1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var range = ss1.getRange('B2:G100');
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  var valuesToSet = [];
  for (var i = 1; i <= numRows; i++) {
    for (var j = 1; j <= numCols; j++) {

      var currentValue = range.getCell(i,j).getValue();
        if( currentValue == "#N/A"|| currentValue == "Loading...") 
        {
          // if formula has not exicuted
         // do nothing, leave the cell as it is
        }
       else
       {
         //remove the formula and set the value
         //range.getCell(i,j).setValue(currentValue);
         // store in an array
          valuesToSet.push([range.getCell(i,j),currentValue])
       }
    }
  }
  //setting values
  for(var rng in valuesToSet)
  {
    valuesToSet[rng][0].setValue(valuesToSet[rng][1]);
  }  
}

修改:更快的方法

{{1}}