Let's say the column of interest is Column A
and I always want to add values in the first row after the last row with values or in the first row if there are no values in the column of interest..
Spreadsheets can deliver several scenarios, they are (if there are others that I haven't listed, remind me in the comments):
- No values in any column (all empty cells):
- Non-empty cells in other columns but not in the column that interest you:
- Non-empty cells in other columns and in the column that interest you:
- Non-empty cells in sequence from the first row in the column you are interested in:
- Non-empty cells from the first row in the column you are interested in but with empty cells between the non-empty cells:
- First cell of the column that interests you being empty but other non-empty cells existing in that same column:
To avoid the crashes that happen in each of these scenarios I've put together these two models that work correctly.
Using the Google Sheets API:
(Need enable the Google Sheets API advanced service)
function gsapi() {
var sheet_id = 'XXXXXXXXXX';
var sheet = SpreadsheetApp.openById(sheet_id);
var sheet_page = sheet.getSheetByName('STACKTEST');
first_row = 1;
var Avals = Sheets.Spreadsheets.Values.get(sheet_id, 'STACKTEST!A' + first_row + ':A').values;
if (Avals != undefined) {
var Alast = Avals.length + 1;
} else {
var Alast = first_row;
}
var to_sheet = [
['A','B','C','D','E']
];
sheet_page.getRange(Alast, 1, to_sheet.length, to_sheet[0].length).setValues(to_sheet);
}
Using Basic Google Apps Script:
function gasbasic() {
var sheet_id = 'XXXXXXXXXX';
var sheet = SpreadsheetApp.openById(sheet_id);
var sheet_page = sheet.getSheetByName('STACKTEST');
first_row = 1;
const lrow = sheet_page.getLastRow();
if (lrow > 0) {
var last = lrow;
} else {
var last = 1;
}
const Avals = sheet_page.getRange("A" + first_row + ":A" + last).getValues();
const reverse = Avals.reverse().findIndex(c=>c[0]!='');
if (reverse != -1) {
var Alast = last - reverse + first_row;
} else {
var Alast = first_row;
}
var to_sheet = [
['A','B','C','D','E']
];
sheet_page.getRange(Alast, 1, to_sheet.length, to_sheet[0].length).setValues(to_sheet);
}
Is there a method that manages to circumvent all these possible scenarios in a more professional way?
It seems a bit archaic to need if
or try + catch
to work around failures.