将工作表复制到另一个电子表格(Google)时出现#REF错误

时间:2018-05-17 17:58:18

标签: google-apps-script google-sheets

我目前正在开发一个脚本,该脚本从另一个电子表格中获取工作表并将其复制到活动的电子表格中。以下是它的工作原理:

  1. 我有一张工作表,用户可以确定原始工作表的名称,原始电子表格的链接以及复制工作表应该获得的名称。

  2. 可以通过两种方式复制工作表: 一个。只有值(使用getValues(); setValues()) 湾用CopyTo

  3. 克隆它

    问题在于第二种方法:

    如果原始工作表具有引用另一个工作表的公式,则i(预期)会出现#ref错误,因为当前电子表格中不存在该引用的工作表。
    理想情况下,本地/内部引用应转换为外部引用。我想一个正则表达式可以用来找到这些公式并在其中插入一个importrange?老实说,我不知道如何对待这件事 有什么想法吗?

2 个答案:

答案 0 :(得分:0)

Cooper意味着使用copyTo(spreadsheet)

在Apps脚本中编写JS脚本
 var source = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = source.getSheets()[0];

 var destination = SpreadsheetApp.openById('ID_GOES HERE');
 sheet.copyTo(destination);

可能有用的附加示例脚本 - Copy Google Spreadsheet Data to another Sheet with Apps Script

答案 1 :(得分:0)

从宏观角度来看,没有用于在工作表中搜索特定类型公式的正则表达式。相反,如果要保留特定公式而不保留其他公式,则需要使用公式检查每个单元格,并确定它是否是要序列化的公式与要保留的公式。然后,如果它是您要序列化的那个,请从源表中读取值并将它们写入副本:

function copyFormulasAndSomeValues() {
  var source = SpreadsheetApp.getActive(). getActiveSheet();
  var remote = SpreadsheetApp.openById("some ID");
  // Copy all static values and formulas (and charts, formatting, etc.)
  var dest = source.copyTo(remote);

  // To efficiently read and write values when we know nothing
  // about the structure of invalid formulas, we will use a RangeList.
  // If structure exists (e.g. if a1 is invalid we know `A2:A100` will be too), we can combine batch
  // get/set methods with the 4 parameter getRange() method.
  var toRead = [];

  // Read in all formulas on the created sheet (no formula appears as "" e.g. nullstring).
  var formulas = copy.getDataRange().getFormulas();
  formulas.forEach(function (row, r) {
    row.forEach(function (formula, c, rowData) {
      if (!formula) return;
      // Check if this is a formula we want to replace.
      if (/* your tests here */) {
        // Store R1C1 notation for later reading.
        toRead.push(String(r + 1) + String(c + 1));
      }
    }); // End column value checking
  }); // End sheet row checking

  // If all formulas checked out, quit.
  if (toRead.length === 0)
    return;

  // Read desired values into a RangeList.
  var rangeList = source.getRangeList(toRead);
  var toWrite = rangeList.getRanges().map(function (range) {
    return range.getValue();
  });

  // Write to the same regions in the destination.
  dest.getRangeList(toRead).getRanges().forEach(function (range, i) {
    range.setValue(toWrite[i]);
  });
}

如果您知道什么是有效/无效的结构/排列,您将能够通过批量读取批量写入静态值来改进此方法。