我有一个脚本,它将运行并仅在B列中用a替换CHA的实例。我想从这里开始替换以下所有内容:
- CHA->A
- CHB->B
- CHC->C
- CHD->D
- PMA->A
- PMB->B
- PMC->C
如果可能 - 双空间""->;"单个空间">
如果一个单元格包含多个实例,我拥有的脚本不会更改所有实例。例如,含有";CHA-CHA";可能只会变为";CHA";,除非脚本运行多次。有没有办法循环脚本并捕获这些?有没有办法让1个脚本更改所有请求的文本?下面是我当前的脚本和谷歌测试表的链接。我们非常感谢您的任何帮助或见解。
function onOpenCHA() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("B1:B");
var to_replace = "CHA";
var replace_with = "A";
replaceInSheetCHA(sheet,range, to_replace, replace_with);
}
function replaceInSheetCHA(sheet, range, to_replace, replace_with) {
//Confirm
var ui = SpreadsheetApp.getUi();
var spread = SpreadsheetApp.getActiveSpreadsheet();
var data = range.getValues();
var oldValue="CHA";
var newValue="A";
var cellsChanged = 0;
for (var row=0; row<data.length; row++) {
for (var item=0; item<data[row].length; item++) {
oldValue = data[row][item];
newValue = data[row][item].replace(to_replace, replace_with);
if (oldValue!=newValue)
{
cellsChanged++;
data[row][item] = newValue;
}
}
}
range.setValues(data);
spread.toast(cellsChanged + " cells changed", "STATUS");
}
https://docs.google.com/spreadsheets/d/1Ox2CcQ6krih80V44HbG724XpIZKAp4BwkbHI2va-fvg/edit?usp=sharing
答案:
您可以使用TextFinder
更改范围内字符串的所有实例
示例代码:
function replace() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var colB = sheet.getRange("B1:B");
var valsToChange = ["CHA", "CHB", "CHC", "CHD", "PMA", "PMB", "PMC", " "];
var changeToArr = ["A", "B", "C", "D", "A", "B", "C", " "];
valsToChange.forEach(function(v, i) {
colB.createTextFinder(v).replaceAllWith(changeToArr[i]);
});
}
此代码的运行情况:
- 获取要替换中字符串的工作表
- 定义要替换的字符串
- 定义要显示的字符串
- 循环遍历范围中的每个字符串,并将其全部替换为相应的替换字符串
参考文献:
- 类文本查找器|应用程序脚本|谷歌开发者