SpreadsheetApp.getActiveSpreadsheet()返回null

时间:2017-07-06 23:05:00

标签: google-apps-script google-sheets

我需要一个快速功能来遍历我的一张纸的行,所以我构建了这个:

function getTotalsOf(name, type) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
  var data = sheet.getDataRange().getValues();
  var total = 0.00;
  for (var i = 0; i < data.length; i++) {
    if (data[i][0]== "") break;
    if (data[i][2] == type) {
      var temp = (Number(data[i][4]) + Number(data[i][5]) + Number(data[i][6])) * data [i][3];
        total = Number(total) + total;
        }
  }
  return total;
}

当我尝试执行该函数时,SpreadsheetApp.getActiveSpreadsheet()似乎返回null。当我尝试通过id获取电子表格时,它也返回null。我错过了什么吗?

编辑: 我使用我的电子表格ID(https://docs.google.com/spreadsheets/d/ STRINGFROMHERE / edit#gid = 1235572150)重试了相同的结果。

function getTotalsOf(name, type) {
  var sheet = SpreadsheetApp.openById("**STRINGFROMURL**").getSheetByName(name);
  var data = sheet.getDataRange().getValues();
  var total = 0.00;
  for (var i = 0; i < data.length; i++) {
    if (data[i][0]== "") break;
    if (data[i][2] == type) {
      var temp = (Number(data[i][4]) + Number(data[i][5]) + Number(data[i][6])) * data [i][3];
        total = Number(total) + temp;
        }
  }
  return total;
}

1 个答案:

答案 0 :(得分:0)

我认为你错过了关于循环电子表格的一些概念。希望这个演示能够帮助你并获得你想要的东西。永远记住电子表格中的行和列以1,1而不是0,0开头。

enter image description here

  function loopThroughCells() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var data = sheet.getDataRange().getValues();
      Logger.log(data[0].length);

  for(var i=0; i< data.length; i++){
    for(var j=0; j<data[i].length; j++){
      if(data[i][j] == "HELIOS"){
           if (data[i][j]== "") break;
           Logger.log("HELIOS data found in range "+ (i+1) + " "+(j+1)); 
      }
    }
  }

日志

[17-07-07 21:45:17:157 HKT] HELIOS data found in range 3 3