I have a sheet where the filter originally started on row 2, so my range was A2:J
. As I've added and deleted rows/columns, my range has changed and it's still changing as I edit the sheet.
Is there a way to name a dynamic range so that if I add/delete columns, my functions will work properly? Kind of like how Sheets/Excel will update formulas if a cell reference is edited.
I have sort by
and set cursor at cell
functions that run onOpen
. However, if I don't manually update the range, then everything gets screwed up every time I open the document. For instance, a few days ago my range was "A6:J" + lr
; my filter was on row 6. I added another header row, making my filter row 7, but the script referenced A6
as the range to sort. This screwed up my data. It's driving me nuts!
Would appreciate some insight on how to reference a dynamic range. Not sure if INDIRECT
or ADDRESS
would work?? Not sure if this answer makes sense?
function onOpen(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA");
var lastRow = ss.getLastRow();
var lastColumn = ss.getLastColumn();
var lastCell = ss.getRange(lastRow, lastColumn);
var range = ss.getRange("A7:" + lastRow);
Logger.log(ss.getRange(lastRow, lastColumn).getDataRegion().getA1Notation());
var columnToSortBy = 2;
var range = ss.getRange("A7:J" + lr);
range.sort( { column : columnToSortBy, ascending: true } );
var r = Math.max.apply(Math, ss.getRange('B:B').getValues()
.map(function (d, i) {
if (d[0]) return i + 1;
}).filter(function (d) {
return d;
})) + 1;
ss.setActiveRange(ss.getRange(r, 2))
}
EDIT: I figured it out! Answer below
Combine .getFrozenRows()+1
with lastRow
and lastColumn
to get a dynamic range that begins after a header row. If a column/row is added/deleted, the range referenced in the function will automatically update. This only works for ranges that begin after a header/filter row, and end with the last filled column.
You can run a log to see if this matches the target range. Run the log below, view log. Then add a row or column, re-run log and compare:
var range = ss.getRange(ss.getFrozenRows()+1, 1, ss.getLastRow(), ss.getLastColumn());
Logger.log("Sorting Range: %s", range.getA1Notation());
StackExchange has provided so many answers for me, so I hope this helps somebody else :) Full explanation with more test logs below.