首页 > 解决方案 > 使用 Google 脚本在另一张完整表格的公式中搜索和替换

问题描述

我使用了一个变体: 在 Google Apps 脚本中创建电子表格备份时,如何复制格式和值,而不是公式?

代码在这里:

function copySheet() {
  var spreadsheetId = "1O6D59wAwzq45fHHPrlZea_cpZsVdlTuct0YgJRD3iyw"; // Please set the source Spreadsheet ID.
  var destFolderId = "18L8k7jtldUQTonp5VO5ZBFd6j_AoC0bj";  // Please set the destination folder ID.

  // Copy each sheet in the source Spreadsheet by removing the formulas as the temporal sheets.
  var ss = SpreadsheetApp.openById(spreadsheetId);
  var tempSheets = ss.getSheets().map(function(sheet) {
    var dstSheet = sheet.copyTo(ss).setName(sheet.getSheetName() + "_temp");
    var src = dstSheet.getDataRange();
    src.copyTo(src, {contentsOnly: false});
    return dstSheet;
  });
  
  // Copy the source Spreadsheet.
  var timeZone = Session.getScriptTimeZone();
  date = Utilities.formatDate(new Date(), timeZone, "YYMMdd");

  var destination = ss.copy(ss.getName() + " - " + date);
  
  // Delete the temporal sheets in the source Spreadsheet.
  tempSheets.forEach(function(sheet) {ss.deleteSheet(sheet)});
  
  // Delete the original sheets from the copied Spreadsheet and rename the copied sheets.
  destination.getSheets().forEach(function(sheet) {
    var sheetName = sheet.getSheetName();
    if (sheetName.indexOf("_temp") == -1) {
      destination.deleteSheet(sheet);
    } else {
      sheet.setName(sheetName.slice(0, -5));
    }
  });

  // Move file to the destination folder.
  var file = DriveApp.getFileById(destination.getId());
  DriveApp.getFolderById(destFolderId).addFile(file);
  file.getParents().next().removeFile(file);
}

function searchReplace() {
  var FILE = SpreadsheetApp.openById("1vb3lv7boclruNyy116CN3oZXeqjUpPl5oFDSakEclDI");
  var textFinder = FILE.createTextFinder('Raw').matchFormulaText(true);
  textFinder.replaceAllWith('Raw');
}

用公式复制整个工作表。我发现的问题是引用其他工作表/选项卡的公式会因“未解决的工作表名称”错误而中断,即使工作表确实存在。

我在这里找到了一种解决方法:https: //support.google.com/docs/thread/25074318/unresolved-sheet-name-workaround-when-copying-or-renaming-tabs?hl=en

并且我希望能够在新复制的工作表中搜索和替换,将公式中的“Raw”一词替换为“Raw”,这将修复损坏的公式,所有这些都来自被复制的工作表中的原始脚本。

我希望这是有道理的,我很想听听任何建议或解决方法...

谢谢

标签: google-apps-scriptgoogle-sheets

解决方案


如果您正在寻找基于应用程序脚本的解决方案,我在这里回答了一个类似的问题。我还写了一个简短的教程来解释这个脚本。但那是关于替换文本的。

您正在寻找在公式中查找和替换。

为此,您需要按如下方式调整我的脚本:

var textFinder = activeSheet.createTextFinder('Raw').matchFormulaText(true);

Raw这将在工作表上的公式中查找文本。

要将其替换为Cooked,脚本的下一行是:

textFinder.replaceAllWith('Cooked');

请参考我以前的答案教程以获取更多信息。


推荐阅读