我正在编写一个脚本来清理电子表格,这些表格是自动生成的,并且包含许多不相关的信息。我需要扫描标题,删除该行,然后删除每隔一行,直到到达完全空白的行,就在下一个标题组之前:
我可以使用下面的代码扫描目标文本并删除行。 我可以记录删除的每一行:Logger.log(“已删除的行:” + toDelete); 但是我在写其余的书时遇到了麻烦
function deleteRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var toDelete = [];
var deleteExtra = [];
var re = new RegExp('(Member Service Associate|Contract Work)','gi');
for (var row = 0; row < values.length; row++) {
for(var column = 0;column<values[row].length;column++){
if (re.exec(values[row][column])){
toDelete.push(row); } } }
for(var deleteRow = toDelete.length-1; deleteRow >= 0;deleteRow--){
sheet.deleteRow(toDelete[deleteRow]+1);
}
Logger.log("deleted rows: " + toDelete );
SpreadsheetApp.flush();
};
记录器输出:
[19-01-02 10:16:13:732 PST]删除的行:33,45,51,54,86,89,101,103,125,127,145,148,171,175,200,208,219,222,262,269,275,280,310,313,324,332,347,352,352,352,363,366,372,374,385,388
答案 0 :(得分:1)
在无法看到电子表格的情况下,您说要一直删除行,直到遇到空白行。
function deleteUnwantedAndAdjacentRows() {
var sh=SpreadsheetApp.getActiveSheet();
var rg=sh.getDataRange();
var vA=rg.getValues();
var d=0;//deleted count
var kd=false;//keep deleting
var re = new RegExp('(Member Service Associate|Contract Work)','gi');
for (var i=0;i<vA.length;i++) {
if(vA[i].join("") && kd){//if something in this row and keep deleting is still true
sh.deleteRow(i-d+1);//then delete
d++;//increment delete count
countinue;//go on to nextrow
}else{//if row is blank
kd=false;//quit deleting
}
for(var j=0;j<vA[i].length;j++){
if(re.exec(vA[i][j])){
sh.deleteRow(i-d+1);
d++;
kd=true;
}
}
}
}
请务必在您可以负担得起的东西上对此进行测试。