CORRECTED
I have a google sheet with a table of weekly data (one year's worth).
At the top of the sheet I have "to" and "from" date fields.
I am trying to restrict the user's view by hiding all columns which relate to dates outside of the "to"/"from" range.
I have researched how to do this but am clearly unable to craft the script correctly.
UPDATE I have now corrected this but my script will only hide the first column no matter what dates I have in the "to"/"from" cells. Script exactly as below.
Thank you.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('NEW - HOURS');
var startColumn = 5;
var values = s.getRange('E7:BD7').getValues();
var start = s.getRange('B4').getValue();
var end = s.getRange('B5').getValue();
var column, len, date, hideCount = 0, showCount = 0;
for (column = values.length - 1; column >= 0; --column) {
date = values[column][0];
if ( typeof date != 'object' || !(date >= start && date < end) ) {
if (showCount) {
s.showColumns(column + startColumn + 1, showCount);
showCount = 0;
}
hideCount++;
} else {
if (hideCount) {
s.hideColumns(column + startColumn + 1, hideCount);
hideCount = 0;
}
showCount++;
}
}
if (showCount) s.showColumns(column + startColumn + 1, showCount);
if (hideCount) s.hideColumns(column + startColumn + 1, hideCount);
}
Be aware that a range is a 2-dimensional array, where the outer array corresponds to the rows, and the nested array to the columns, as can be withdrawn from the method getRange(row, column).
As a consequence, the values
matrix is defined as values[row][column]
, and values.length
will give you the number of rows - for the number of columns use values[0].length
.
In summary, you need to change
for (column = values.length - 1; column >= 0; --column) {
date = values[column][0];
...
to
for (column = values[0].length - 1; column >= 0; --column) {
date = values[0][column];
...
ADDITIONAL UPDATE:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('NEW - HOURS');
var startColumn = 5;
var values = s.getRange('E7:7').getValues();