How to refresh a sheet's cell value in Google Apps Script

后端 未结 5 1279
囚心锁ツ
囚心锁ツ 2020-12-16 15:02

I\'m experimenting with Blockspring which provides a Google Sheets add-on which can, for example, run a function which returns data from a webservice e.g.

=B         


        
5条回答
  •  独厮守ぢ
    2020-12-16 15:18

    Posting a useful snippet, in case you need to force all formulas to recalculate. This is considerably more performant than other examples posted here.

    function forceRefreshSheetFormulas(sheetName) {
      var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = activeSpreadsheet.getSheetByName(sheetName);
      var range = sheet.getDataRange();
      var numCols = range.getNumColumns();
      var numRows = range.getNumRows();
      var rowOffset = range.getRow();
      var colOffset = range.getColumn();
    
      // Change formulas then change them back to refresh it
      var originalFormulas = range.getFormulas();
    
      //Loop through each column and each row in the sheet
      //`row` and `col` are relative to the range, not the sheet
      for (row = 0; row < numRows ; row++){
        for(col = 0; col < numCols; col++){
          if (originalFormulas[row][col] != "") {
            range.getCell(row+rowOffset, col+colOffset).setFormula("");
          }
        };
      };
      SpreadsheetApp.flush();
      for (row = 0; row < numRows ; row++){
        for(col = 0; col < numCols; col++){
          if (originalFormulas[row][col] != "") {
            range.getCell(row+rowOffset, col+colOffset).setFormula(originalFormulas[row][col]);
          }
        };
      };
      SpreadsheetApp.flush();
    };
    

    There are a few tricks at work: - Setting a cell's formula to "" clears it, so we avoid that. - We need to change the formula, flush, and change it back and flush again.

提交回复
热议问题