Dates can be a little tricky. See This question to get a better idea. But this script can at least get you started.
This Google Sheet demonstrates a custom formula (AGEGROUP
) to compare the input date to a "age-groups" sheet.
Note: Only add to "age-groups" sheet if needed.
The last row with a value is used to consider if someone is too old.
The first row of the sheet is used to see if someone is too young.
AGEGROUP()
will accept a cell reference to look up
Example AGEGROUP(B2)
would check cell B2, assuming it contains a date, and return a group assignment (U 5, U 6, U7...).
Looking up dates manually (instead of referencing another cell) can be accomplished by nesting DATE
inside of AGEGROUP
. You must follow the right arguments for DATE
(year, month, day).
Example AGEGROUP(DATE(2010,1,21))
I'm new to custom functions and did not look into the options for supporting function details like @param
or @return
and so on.
Apps Script
/**
* Finds age group of the input value (date).
*
* @param {date} Input the date to compare to date ranges.
* @return Returns age groupd based on provided date.
* @customfunction
*/
function AGEGROUP(date) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var ages = ss.getSheetByName("age-groups");
var range = ages.getDataRange();
var values = range.getValues();
var i = 0;
var ranges = values.length;
var lastRow = ranges -1;
// loop through dateRanges
for(i; i < ranges; i++) {
// if date in AGEGROUP()
if(date >= values[i][1] && date <= values[i][2]) {
// return age group
return values[i][0];
}
// if child is too old
if(date > values[0][2]) {
return "Child is too young.";
}
// if child is too young
if(date < values[lastRow][1]) {
return "Child is too old.";
}
}
}