Google Spreadsheets脚本可删除找到字符串的所有行

时间:2015-02-11 18:49:40

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

我需要遍历工作表中的所有行/列,并删除包含某些单词的行。理想情况下,我会使用正则表达式搜索工作表,但只是找到一个字符串将有助于我移动。我在Stack Overflow上看到很多关于查找和删除空行的帖子,但找不到有关搜索整个工作表和删除行的任何信息。

这是我到目前为止所做的:

/* Delete rows */
function deleteRows() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  var deleted = 0;  // Counter (don't need if we loop backwards)
  var regExp = new RegExp('word');

  for (var row = 0; row < values.length; row++) {
    var regExpMatch = values[row][1].match(regExp);
    if (regExpMatch.length > 0) {
      sheet.deleteRow(row + 1 - deleted);
      deleted++;
    }
  }
  SpreadsheetApp.flush();
};

然而,这仅搜索B列,并且它会抛出错误“TypeError:无法从null读取属性'长度',即使我的电子表格中的B列中存在”word“。如果我做一个更简单的版本,如:

/* Delete rows */
function deleteRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  var deleted = 0;  // Counter (don't need if we loop backwards)

  for (var row = 0; row < values.length; row++) {
    if (values[row][1].search("WordThatExistsInOneRow")) {
      sheet.deleteRow(row);
      deleted++;
    }
  }
  SpreadsheetApp.flush();
};

它开始删除每一行,即使“WordThatExistsInOneRow”仅显示在一行中。

1 个答案:

答案 0 :(得分:2)

你没有正确编写你的循环逻辑,你需要遍历每一行,然后循环该行中的每一列,然后分配行索引以进行删除,这必须以崇敬的顺序执行。试试这个:

/* Delete rows */
function deleteRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  var toDelete = [];

  for (var row = 0; row < values.length; row++) {
    for(var column = 0;column<values[row].length;column++){
      if (values[row][column].indexOf("WordThatExistsInOneRow") > -1){
        toDelete.push(row);
      }
    }
  }

  for(var deleteRow = toDelete.length-1; deleteRow >= 0;deleteRow--){
    sheet.deleteRow(toDelete[deleteRow]+1);
  }

  SpreadsheetApp.flush();
};