Determining the last row in a single column

前端 未结 19 1286
野性不改
野性不改 2020-11-22 10:46

I have a sheet with data in cols A through H.

I need to determine the last row in column A that contains data (it\'s all conti

19条回答
  •  北海茫月
    2020-11-22 11:00

    This will get the last row in a sheet assuming based on column A.

    function getLastDataRow(sheet) {
      var lastRow = sheet.getLastRow();
      var range = sheet.getRange("A" + lastRow);
      if (range.getValue() !== "") {
        return lastRow;
      } else {
        return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
      }              
    }
    

    This fixes @mrityunjay-pandey partially-correct answer.

    To extend this answer to get the last row and column, we can use:

    function columnToLetter(column) {
      var temp, letter = '';
      while (column > 0) {
        temp = (column - 1) % 26;
        letter = String.fromCharCode(temp + 65) + letter;
        column = (column - temp - 1) / 26;
      }
      return letter;
    }
    
    function letterToColumn(letter) {
      var column = 0, length = letter.length;
      for (var i = 0; i < length; i++) {
        column += (letter.charCodeAt(i) - 64) * Math.pow(26, length - i - 1);
      }
      return column;
    }
    
    function getLastDataColumn(sheet) {
      var lastCol = sheet.getLastColumn();
      var range = sheet.getRange(columnToLetter(lastCol) + "1");
      if (range.getValue() !== "") {
        return lastCol;
      } else {
        return range.getNextDataCell(SpreadsheetApp.Direction.PREVIOUS).getColumn();
      }              
    }
    
    function getLastDataRow(sheet) {
      var lastRow = sheet.getLastRow();
      var range = sheet.getRange("A" + lastRow);
      if (range.getValue() !== "") {
        return lastRow;
      } else {
        return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
      }              
    }
    
    function run() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var [startRow, lastRow] = [2, getLastDataRow(sheet)];
      var [startCol, lastCol] = [1, getLastDataColumn(sheet)];
    }
    

提交回复
热议问题