google-apps-script - 使用 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”,这将修复损坏的公式,所有这些都来自被复制的工作表中的原始脚本。
我希望这是有道理的,我很想听听任何建议或解决方法...
谢谢
解决方案
如果您正在寻找基于应用程序脚本的解决方案,我在这里回答了一个类似的问题。我还写了一个简短的教程来解释这个脚本。但那是关于替换文本的。
您正在寻找在公式中查找和替换。
为此,您需要按如下方式调整我的脚本:
var textFinder = activeSheet.createTextFinder('Raw').matchFormulaText(true);
Raw
这将在工作表上的公式中查找文本。
要将其替换为Cooked
,脚本的下一行是:
textFinder.replaceAllWith('Cooked');
推荐阅读
- linux - 无法在 CentOS 中使用 docker run 命令
- php - php_network_getaddresses:getaddrinfo 失败:不知道这样的主机
- c# - 我的模型的所有属性在 post 方法中都是 null
- django - 简单的站点搜索 django
- ios - 在 Objective-C 中使用 SCRecorder 以修改后的播放速度保存视频
- c - 如何计算结构的大小?
- python - 使用单个 GPU 的 xgboost 失败
- generics - 是否有任何语言在作为参数传递的函数上实现保留的泛型?
- c++ - 显式 range-v3 decltype 评估为无效?
- ruby-on-rails - Rails:是否可以在主页上向用户展示特色列?必须禁用 uglifier 才能让 chartkick 在 heroku 上工作?