Google apps script 强制Google电子表格公式重新计算

Google apps script 强制Google电子表格公式重新计算,google-apps-script,google-sheets,custom-function,Google Apps Script,Google Sheets,Custom Function,我以前知道这个问题,但给出的答案对我的案例无效,因为它略有不同 我创建了一个公式,用于查找名称中带有图案的图纸,然后使用其内容生成输出。比如说 function sampleFormula(searchTerm) { const spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); const sheets = spreadsheet.getSheets() .filter(function(sheet) { //

我以前知道这个问题,但给出的答案对我的案例无效,因为它略有不同

我创建了一个公式,用于查找名称中带有图案的图纸,然后使用其内容生成输出。比如说

function sampleFormula(searchTerm) {
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const sheets = spreadsheet.getSheets()
    .filter(function(sheet) {
      // If sheet name starts with DATA_SHEET_...
      return sheet.getSheetName().indexOf('DATA_SHEET_') === 0;
    });

  const result = [];

  sheets.forEach(function(sheet) {
    // We get all the rows in the sheet
    const rows = sheet.getDataRange().getValues();

    rows.forEach(function(row) => {
      // If the row it's what we are looking for we pick the columns A and C
      if (row[1] === searchTerm) {
        result.push([ row[0], row[2] ])
      }
    });
  });

  // If we found values we return them, otherwise we return emptry string
  return result.length ? result : '';
}
问题是,当名称以
DATA\u sheet\u开头的工作表中的单元格发生更改时,我需要重新计算此公式

我看到的大多数答案(我通常做的)是通过我们想要观察的范围作为公式的参数,即使它没有被使用。但在这种情况下,它将不起作用,因为我们不知道我们正在观察多少范围,甚至不知道整个工作表名称(它是由使用谷歌电子表格API的web服务注入的)

我原以为Google脚本会有类似于
range.watch(公式)
range.onChange(这个)
的东西,但我找不到类似的东西

我还尝试创建一个简单的函数来更改每个公式所依赖的cell
B2
的值,但我需要立即将其恢复,这样就不会将其视为更改(如果我实际更改它,所有公式都将中断):


所以我不知道我还能做什么,我在多个工作表上有100个公式这样做,当我修改
数据工作表…
工作表时,它们不会更新。

要强制重新计算自定义函数,我们可以使用“触发参数”,它唯一的目的是触发自定义函数的重新计算。这个触发参数可以是一个单元格引用,它将由一个简单的编辑触发器更新,或者我们可以使用一个编辑可安装触发器来更新所有公式

使用单元格引用作为触发参数的示例

=sampleFormula("searchTerm",Triggers!A1)
使用编辑可安装触发器更新所有公式的示例

假设公式具有以下形式,保存公式的单元格是Test!A1和测试!F5

=sampleFormula("searchTerm",0)
其中0将被
sampleFormula
忽略,但将使其重新计算

设置编辑可安装触发器以触发以下功能

function forceRecalculation(){
  updateFormula(['Test!A1','Test!F5']);
}
将进行更新的函数可能如下所示:

function updateFormula(references){
  var rL = SpreadsheetApp.getActive().getRangeList(references);
  rL.getRanges().forEach(function(r){
    var formula = r.getFormula();
    var x = formula.match(/,(\d+)\)/)[1];
    var y = parseInt(x)+1;
    var newFormula = formula.replace(x,y.toString());
    r.setFormula(newFormula);
  });
}

正如您所想象的,使用单元格引用作为触发参数会比使用单元格引用慢一些,但在某些情况下可能会更方便。

包含这些公式的单元格是随机放置的,还是始终是正方形范围(连续的列和行集)?此外,我是否正确理解数据表值会自动更新?公式放置在不同的非相邻单元格中。数据表中有些列手动更新,有些列自动更新。
function updateFormula(references){
  var rL = SpreadsheetApp.getActive().getRangeList(references);
  rL.getRanges().forEach(function(r){
    var formula = r.getFormula();
    var x = formula.match(/,(\d+)\)/)[1];
    var y = parseInt(x)+1;
    var newFormula = formula.replace(x,y.toString());
    r.setFormula(newFormula);
  });
}