在特定列中获取最后一个值的有效方法

时间:2016-10-14 15:52:44

标签: google-apps-script

我编写了一个函数来获取Google表格中单个列中的最后一个值。

// Returns the row number of the first empty cell
// Offset should be equal to the first row that has data
function getLastRowInColumn(sheet, column, rowOffset) {
  var lastRow = sheet.getMaxRows();
  for (var row = rowOffset; row < lastRow; row++) {
    var range = sheet.getRange(row, column);
    if (range.isBlank()) {
      return row;
    };
  }
}

我可以假设所有值都已填写,因此该函数实际上返回它找到的第一个空单元格(在这种情况下,这相当于第一个空行)。

该函数需要很长时间才能运行~1000行的工作表。我怎样才能提高效率呢?

提前致谢。

2 个答案:

答案 0 :(得分:0)

在这里查看类似问题的答案。它是关于获得第一个空行,你只是一个更高。 Faster way to find the first empty row

答案 1 :(得分:0)

将所有数据读入本地数组并读取,只需记住该行将是零索引(从0开始)而不是从1开始的行号:

// Returns the row number of the first empty cell
// Offset should be equal to the first row that has data
function getLastRowInColumn(sheet, column, rowOffset) {
  var lastRow = sheet.getMaxRows();
  var data = sheet.getDataRange().getValues()
  for (var row = rowOffset; row < lastRow; row++) {
    if (data[row][0] === '') {
      return row;
    };
  }
}