我的工作表中的许多单元格条目包含我要删除的无关单词。我需要一个脚本来查找单个列中的关键字(在本例中为" B")并按顺序删除它们。目标是缩短单元格条目。
我的关键词是" Epic Artifactory DIY"," Barn"," Planks"," Pack,"优惠券:WTXPXZP&#34 ;,"优惠券:FREESHIP50","优惠券:SPRING10"和" Wall"。
我找到了这个脚本,但它对我不起作用。
function fandr() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getActiveSheet();
var r=s.getDataRange();
var vlst=r.getValues();
var i,j,a,find,repl;
find="abc";
repl="xyz";
for (i in vlst) {
for (j in vlst[i]) {
a=vlst[i][j];
if (a==find) vlst[i][j]=repl;
}
}
r.setValues(vlst);
}
由于
答案 0 :(得分:3)
以下是一些只在一列中获取数据的代码,并用空字符串替换所有内容(删除单词)。替换Google表格一列中的单词。
function replaceInColumn() {
var arrayWordsToFind,dataInColumn,dataAsString,newString,
newData,outerArray,i,lastrow,L,sh,ss,tempArray,toFind;
arrayWordsToFind = [
"Epic Artifactory DIY", "Barn", "Planks", "Pack",
"Coupon: WTXPXZP", "Coupon: FREESHIP50", "Coupon: SPRING10", "Wall"
]
ss = SpreadsheetApp.getActiveSpreadsheet();
sh = ss.getSheetByName("Your Sheet Name Here");
lastrow = sh.getLastRow();//Get row number of last row
//sh.getRange(start row, start column, number of Rows, number of Columns)
dataInColumn = sh.getRange(2, 2, lastrow).getValues();
dataAsString = dataInColumn.toString();//Convert 2D array to a string
//Logger.log('dataAsString: ' + dataAsString)
newString = dataAsString;
L = arrayWordsToFind.length;//The number of words to find
for (i=0;i<L;i++) {//Loop once for every word to find
toFind = new RegExp(arrayWordsToFind[i], "g");//define new Reg Ex with word to find - replace globally
newString = newString.replace(toFind,"");//Delete all found words
}
//Logger.log('newString: ' + newString)
newData = newString.split(",");//Convert string to 1D array
outerArray = [];
L = newData.length;
for (i=0;i<L;i++) {
//Logger.log('i: ' + i)
//Logger.log('newData[i]: ' + newData[i])
tempArray = [];//Reset
tempArray.push(newData[i]);
outerArray.push(tempArray);//Create a new 2D data array
}
sh.getRange(2, 2, outerArray.length).setValues(outerArray);
}
关键词:查找替换列全局
答案 1 :(得分:0)
此Google脚本功能可帮助您查找和替换特定列中所有单元格的文本(在本例中为B)。
function findReplace() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var column = 2;
for (var d=0, l=data.length; d<l; d++) {
if (data[d][column-1] === "find") {
sheet.getRange(d+1, column).setValue("replace");
}
}
SpreadsheetApp.flush();
}