Is there a faster way to refresh all of my custom formulas?

时光总嘲笑我的痴心妄想 提交于 2020-08-17 06:00:09

问题


I need to refresh all of my custom formulas via a script in Google Sheets but this seems to take forever (like, 30 seconds for 100 cells). There will potentially be thousands of cells with my custom formula so I must come up with a better way. I have:

function refresher(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var selection = sheet.getDataRange();
  var columns = selection.getNumColumns();
  var rows = selection.getNumRows();
  for (var column=1; column <= columns; column++){
    for (var row=1; row <= rows; row++){
      var cell=selection.getCell(row,column);
      var formula = cell.getFormula();
      if (formula.startsWith("=myfunc(")){
        cell.setFormula(formula.replace("=myfunc(", "?myfunc("));
      }
    }
  }
  SpreadsheetApp.flush();
  for (var column=1; column <= columns; column++){
    for (var row=1; row <= rows; row++){
      var cell=selection.getCell(row,column);
      var formula = cell.getFormula();
      if (formula.startsWith("=?myfunc(")){
        cell.setFormula(formula.replace("=?myfunc(", "=myfunc("));
      }
    }
  }
}

回答1:


In order to achieve your goal, how about using TextFinder? In this case, I think that the process cost might be able to be reduced. From your script, when TextFinder is used for your situation, it becomes as follows.

Sample script:

function refresher() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const formula = "=myfunc";
  const tempFormula = "=sampleFormula";
  sheet.createTextFinder("^\\" + formula).matchFormulaText(true).useRegularExpression(true).replaceAllWith(tempFormula);
  sheet.createTextFinder("^\\" + tempFormula).matchFormulaText(true).useRegularExpression(true).replaceAllWith(formula);
}

Reference:

  • Class TextFinder


来源:https://stackoverflow.com/questions/61946438/is-there-a-faster-way-to-refresh-all-of-my-custom-formulas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!