Answers / Question 23

Apps Script appendRow() and getLastRow() land at row 1001: checkboxes and formulas count as data

Why appendRow() and getLastRow() skip past hundreds of empty-looking rows when a tab has checkboxes or formulas filled down, and a tested script that writes under the last row of one column instead.

The problem

Your script adds a row with appendRow(), or writes to getLastRow() + 1, and it used to land right under your data. Now new rows show up at row 1001, far below everything else, with hundreds of empty-looking rows in between. Nothing in the script changed; someone added a checkbox column, or filled a formula down the tab.

Inspired by a public question on Stack Overflow. The problem above is described in our own words and the solution below is ours.

Why it happens

getLastRow() returns the last row that has any content in any column, and appendRow() writes just below that row. A cell can look empty and still count as content:

So the script isn't wrong; it's asking the wrong question. You want the last row of one column that only real entries fill, such as the date or name column.

The fix: find the last row in one column, then write there

The script below reads one key column, walks up from the bottom to the last cell with a real value (cells holding only spaces count as empty), and writes your new rows straight under it in a single call. It only writes the columns you give it, so a checkbox column or ARRAYFORMULA column further right keeps working. If the tab is full, it adds rows first.

  1. Extensions → Apps Script, paste the code, and set TARGET: the tab name, the key column (a column every real row has a typed value in) and how many header rows there are.
  2. In your own code, replace sheet.appendRow([a, b, c]) with appendBelowLast([[a, b, c]]). You can pass several rows at once: appendBelowLast([[a, b], [c, d]]).
  3. Run testAppend once to check where a row lands, then delete the test row.
Code.gsApps Script
// Add rows under the last row that has a value in ONE column, instead of under
// sheet.getLastRow(). Checkboxes, copied-down formulas and ARRAYFORMULA output in
// other columns are ignored, so new rows stop landing at row 1001.
const TARGET = {
  sheet: 'Log',        // tab to write to
  keyColumn: 1,        // a column every real row has a typed value in (1 = A)
  firstColumn: 1,      // first column you write to (1 = A)
  headerRows: 1        // rows at the top to never write over
};

// Last row (number) with something in column `col`, at or below `firstRow`.
// Blank strings and cells holding only spaces count as empty.
function lastRowInColumn_(sheet, col, firstRow) {
  const last = sheet.getLastRow();
  if (last < firstRow) return firstRow - 1;
  const values = sheet.getRange(firstRow, col, last - firstRow + 1, 1).getValues();
  for (let i = values.length - 1; i >= 0; i--) {
    const v = values[i][0];
    if (v !== null && String(v).trim() !== '') return firstRow + i;
  }
  return firstRow - 1;
}

// Writes `rows` (an array of arrays) in one call, starting on the first free row.
// Only the columns you pass are written, so checkbox and formula columns to the
// right are left alone. Returns the row number the first new row went to.
function appendBelowLast(rows) {
  const sheet = SpreadsheetApp.getActive().getSheetByName(TARGET.sheet);
  if (!sheet) throw new Error('No tab named "' + TARGET.sheet + '"');
  if (!rows || !rows.length) return 0;
  const width = rows.reduce(function (m, r) { return Math.max(m, r.length); }, 0);
  const data = rows.map(function (r) { const o = r.slice(); while (o.length < width) o.push(''); return o; });
  const start = lastRowInColumn_(sheet, TARGET.keyColumn, TARGET.headerRows + 1) + 1;
  const missing = start + data.length - 1 - sheet.getMaxRows();
  if (missing > 0) sheet.insertRowsAfter(sheet.getMaxRows(), missing);   // grow the tab if needed
  sheet.getRange(start, TARGET.firstColumn, data.length, width).setValues(data);
  return start;
}

// Try it: adds one test row and logs where it went.
function testAppend() {
  const row = appendBelowLast([[new Date(), 'Test entry', 1]]);
  console.log('Wrote to row ' + row);
}

Need the number in a cell instead?

These formulas return the last row in column A that holds a value, and they ignore the other columns:

Excel (any version)Formula
=LOOKUP(2,1/(A2:A1000<>""),ROW(A2:A1000))
Google Sheets, whole column (returns 1 if the column is empty)Formula
=IFERROR(MAX(FILTER(ROW(A2:A),A2:A<>"")),1)

Avoid =COUNTA(A2:A)+1 for this: it is one row short for every gap in the column.

Good to know

The script's logic is unit-tested against a simulated spreadsheet before publishing. Always try new automations on a copy of your sheet first.