从过滤数据循环遍历每一行

时间:2019-07-15 15:13:52

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

我正在尝试运行一个简单的脚本,该脚本将在满足某些条件(即第8列为0)的每一行上循环。过滤有效,因为我可以看到过滤器已正确应用,但是代码始终使用未经过滤的数据版本,因此始终循环工作表中的所有行。

// Get sheet
var sheet = SpreadsheetApp.openById("<sheetId>").getSheetByName("Log");

// Filter out all items that have already been revoked. (this works)
var filterCriteria = SpreadsheetApp.newFilterCriteria().setHiddenValues(["1"]).build();
var pendingRevocations = sheet.getRange("A:J").createFilter().setColumnFilterCriteria(8, filterCriteria);

// Loop through each to remove these permissions
for each (var pendingRevocation in pendingRevocations){

  // This doesn't work. I've tried various ways, and in all of them
  // I either get ALL rows (unfiltered) or just an odd selection of 
  // blank rows

  // Do stuff with pendingRevocation
  var name = pendingRevocation[9];
  Logger.log("Name:" + name);

}

我确定这必须很容易实现,我在做什么错了?

2 个答案:

答案 0 :(得分:2)

该过滤器可隐藏工作表中的行,但不能用于过滤脚本中的行。

请尝试使用getDataRange()方法[1]获取所有数据并遍历数据,同时将if条件应用于过滤器:

  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var data = ss.getDataRange().getValues();

  for (var i = 0; i < data.length; i++) {
    if (data[i][7] == 0) {
      // Do stuff
    }
  }

[1] https://developers.google.com/apps-script/reference/spreadsheet/sheet#getdatarange

答案 1 :(得分:0)

如果过滤器不是来自脚本,则还有.isRowHiddenByFilter()method(他们的文档中有错误,它只是先前方法的复制/粘贴...)

也可能有用,因为“删除权限”注释可能意味着您想做的不只是日志工作?

您可以这样做:

document.getElementById("config-select").addEventListener("input", function() {
  const doc_select = document.getElementById("config-select");
  const doc_name = doc_select.value;
  // check if the doc name exists: returns doc id
  nameExists(doc_name).then(function(doc_obj) {
//^^^^^^^^^^^^^^^^^^^^^^^^^^          ^^^^^^^
    console.log("then", doc_obj);
    if (doc_obj.bool) { // it does exist:
      alert("replacing id");
    } else { // it doesn't:
      alert("resetting id");
    }
    doc_select.setAttribute("doc-id", doc_obj.id); // id is "" when it doesn't exist
  }).catch(function (err) {
    console.log(err);
  })
});