google sheets calulation latency and dependant function calls

前端 未结 1 573
感动是毒
感动是毒 2021-01-27 08:30

Here is a function that pupulates a column with a formula:

function fillAccount(lastRow) {

  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRang         


        
相关标签:
1条回答
  • 2021-01-27 09:04

    First of all, your function needs a bit of cleanup (it can be done refined further, but that's a start):

    function fillAccount(lastRow) {
      var spreadsheet = getSpread(); //custom method calling the Spreadsheet, change to your logic;
    
      var colB = spreadsheet.getRange('B1:B'+lastRow);
      var row1 = colB.getCell(1,1);
      var row2 = colB.getCell(2,1);      
    
      row1.setValue(' ');
      row2.setFormula('=ifna(vlookup(C2,RENAMED!$A$1:$A$7,1,false),B1)');
      row2.copyTo(colB.offset(1,0,lastRow-1), SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
    
      SpreadsheetApp.flush(); //make sure changes are applied;      
    }
    

    Then, simply call the second function and make sure you access values to ensure calculation (if you have a pretty long latency (e.g. > 1s for each formula calc), some formulas might end up with #ERROR! value - if you want to account for that, add check ==='#ERROR!' that terminates second function upon encountering such a value and recursively restarts it):

    /**
     * Caller function;
     */
    function triggerFill() {
    
      //...your logic and lastRow initialization here;
    
      fillAccount(lastRow);
      copyAllData();
    }
    
    /**
     * Function accessing updated values;
     */
    function copyAllData() {
      var spreadsheet = getSpread(); //custom method calling the Spreadsheet, change to your logic;
      var dataRange = spreadsheet.getDataRange(); //just an example that gets all data;
      var values = dataRange.getValues(); //just an example that gets all values;
      for(var i=0; i<values.length; i++) {
        if(values[i].indexOf('#ERROR!')!==-1) { //for high latency;
          Utilities.sleep(t) //change t to number of ms to wait to your liking;
          return copyAllData();
        }
      }
    
      //do other stuff, like cell copy;
    }
    
    0 讨论(0)
提交回复
热议问题