Google表格脚本-删除包含特定数据的行

时间:2019-06-10 12:31:25

标签: javascript google-apps-script google-sheets

因此,我有一个代码可以从电子表格中删除包含特定单词的行。 如何不仅将其应用于一列并仅搜索一个单词,而且还要检查几列和几个单词?

function sort() { 
  var sheet = SpreadsheetApp.getActiveSheet(); 
  var rows = sheet.getDataRange(); 
  var numRows = rows.getNumRows(); 
  var values = rows.getValues(); 
  var rowsDeleted = 0; 

  for (var i = 0; i <= numRows - 1; i++) { 
    var row = values[i]; 
    if (row[21].indexOf('Wohnmobil') > -1) { 
      sheet.deleteRow((parseInt(i)+1) - rowsDeleted); rowsDeleted++; 
    } 
  } 
};

使用此代码,它可以浏览第V列并删除带有单词“ Wohnmobil”的行。

例如如何检查R和V列,并删除包含“ Wohnmobil”,“ WG”,“ Trailer”,“ Caravan”等单词的行?

1 个答案:

答案 0 :(得分:0)

您可以尝试一下,

function sort() { 
  var sheet = SpreadsheetApp.getActiveSheet(); 
  var rows = sheet.getDataRange(); 
  var values = rows.getValues(); 
  var rowsDeleted = 0; 
  var arrayOfWords = ['Wohnmobil', ....] //this is your array of words to search

  for (var i = values.length - 1; i >= 0; i--) {  
    var row = values[i]; 
    for (var j = 0; j < arrayOfWords.length; j++) {    //loop thru your word list
      if (row.indexOf(arrayOfWords[j]) > -1) {         // search every column 
        sheet.deleteRow(i+1);     //since i loop runs from bottom row, you don't need to account for row number changes 
        rowsDeleted++;   
        break; //go out of j loop since a word has already been found and the row deleted        
      }
    } 
  } 
};