【问题标题】:Search & Replace within formula of another entire sheet using Google script使用 Google 脚本在另一张完整表格的公式中搜索和替换
【发布时间】:2021-09-24 01:58:26
【问题描述】:

我使用了这个的变体:How to copy format and values, not formulas, when creating a spreadsheet backup in Google Apps Script?

代码在这里:

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”,这将修复损坏的公式,所有这些都来自被复制工作表的原始脚本。

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

谢谢

【问题讨论】:

  • 你是如何复制这些公式的?如果可能,请发布一个显示这一点的 sn-p,以便其他人更容易提供帮助。

标签: google-apps-script google-sheets


【解决方案1】:

如果您正在寻找基于应用程序脚本的解决方案,我回答了 similar question here。我还写了一个short tutorial 解释脚本。但那是关于替换文本的。

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

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

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

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

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

textFinder.replaceAllWith('Cooked');

请参考我的previous answertutorial 了解更多信息。

【讨论】:

  • 太棒了,感谢 ADW 完美运行!唯一的问题是每次创建新副本时文件 ID 都会有所不同。有没有一种简单的方法可以将您的代码集成到我的 copySheet 函数中,这样我就不需要文件 ID? (我已经用我的代码更新了我的问题)...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多