将状态添加到 for 循环中的每个 proccesed 行,该循环具有带有 Google App Script 的 if 语句

Add a status to each proccesed row in for loop that has an if statement with Google App Script

我在 App 脚本中有一个 for 循环,它只查看两列中有数据的行。我想在实际处理的每一行上设置一个状态,但状态被添加到错误的行。当我添加到 i 时,它会添加到数组的整个长度,所以我想我不应该尝试处理每一行,我做错了什么?

    function auditReport() {
  var sheetname = "Sheet1"; // name of data sheet ex. Form Responses 1
  var colstoworkon = 10; // how many cols are filled with data f.e. by a form
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.setActiveSheet(ss.getSheetByName(sheetname));
  var sheet = ss.getSheetByName(sheetname);
  var data = sheet.getRange(3,1,sheet.getLastRow()-1,colstoworkon).getValues(); // starting with row 2 and column 1 as our upper-left most column, 

  //This makes it loops continuously and checks all not done rows
for (var i in data) {
  
    if(data[i][1] && data[i][2]){//if email or copy are undefined just skip

  var setStatus = sheet.getRange(i,4).setValue("done")


            } // end of if
      } // End of Loop
} //End of email function

修改点:

  • 在您的脚本中,从 getRange(3,1,sheet.getLastRow()-1,colstoworkon) 开始,在这种情况下,它必须是 getRange(3,1,sheet.getLastRow()-2,colstoworkon)
  • for (var i in data) {的情况下,i是字符串类型。
  • 如果要使用sheet.getRange(i,4).setValue("done"),则需要sheet.getRange(Number(i) + 3, 4).setValue("done")
    • 我认为这可能是您 but the statuses get added to the wrong rows. 问题的原因。
  • if (data[i][1] && data[i][2]) {的情况下,如果值为0data[i][1] && data[i][2]就是false

当这些点反映到你的脚本中,就变成了下面这样。

修改后的脚本:

function auditReport() {
  var sheetname = "Sheet1";
  var colstoworkon = 10;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.setActiveSheet(ss.getSheetByName(sheetname));
  var sheet = ss.getSheetByName(sheetname);
  var data = sheet.getRange(3, 1, sheet.getLastRow() - 2, colstoworkon).getDisplayValues();
  for (var i in data) {
    if (data[i][1] && data[i][2]) {
      var setStatus = sheet.getRange(Number(i) + 3, 4).setValue("done");
    }
  }
}

或者,你的脚本也可以修改如下。在此修改中,done 使用范围列表放置。这样一来,工艺成本可以降低一点。

function auditReport() {
  var sheetname = "Sheet1";
  var colstoworkon = 10;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.setActiveSheet(ss.getSheetByName(sheetname));
  var sheet = ss.getSheetByName(sheetname);
  var data = sheet.getRange(3, 1, sheet.getLastRow() - 2, colstoworkon).getDisplayValues();
  var ranges = data.map(([,b,c], i) => b && c ? `D${i + 3}` : "").filter(String);
  if (ranges.length == 0) return;
  sheet.getRangeList(ranges).setValue("done");
}

参考文献: