如何将范围设置为电子表格中的最后一行数据?使用Google Apps脚本

时间:2015-02-07 09:58:59

标签: google-apps-script

如何更改变量"范围"是输入电子表格的最后一行数据,而不是' A2:Z2'?

function findFault() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Inspections");

  //Set the range to be search through 
  var range = sheet.getRange('A2:Z2');

  //Turn the range into data values
  var data = range.getValues();

  //Declare fault and the value to search for
  var fault = "Fault";

  //Iterate through data to find fault
  for (var i = 0; i < data.length; i++) {
    for (var j = 0; j < data[i].length; j++) {
      if (data[i][j] == fault) {

        //log to test if working
        Logger.log("Found Fault");
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

我更新了我的代码并使其正常运行。如果有人有提高效率的提示,请发帖。

function findFault() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Inspections");

  //Get the last row if data
  var lastRowNumber = sheet.getDataRange().getNumRows();
  var allColumns = sheet.getDataRange().getNumColumns();

  //Set the range to be search through 
  var range = sheet.getRange(lastRowNumber, 1, 1, allColumns);

  //Turn the range into data values
  var data = range.getValues();

  //Declare fault and the value to search for
  var fault = "Fault";


  //Iterate through data to dinf fault
  for (var i = 0; i < data.length; i++) {
    for (var j = 0; j < data[i].length; j++) {
      if (data[i][j] == fault) {

        //log to test if working
        Logger.log("Found Fault");
      }
    }
  }
}