I have calendar data in my spreadsheet. Each row is a day, and each column is a half-hour increment of time from that day.
When I add events to the calendar I block off the time by merging the relevant columns.
The calendar data is in the range B3:Y77
.
In a separate column AA
I have a list of event names that match events found in the calendar.
In column AD
I want to return the number of cells that are merged in the calendar by the event listed in AA
.
For example, if the event is in a merged cell that includes three columns, the value returned would be 3
. If the event is in a single unmerged cell 1
would be returned.
I almost succeeded using the Google Apps Script below. It returns the correct value however it only works when I first enter the formula into AD
. It doesn't update if I change the event.
For example, I would call the function ContaCelleUnite
in AD3
using the formula =ContaCelleUnite(AA3;"B3:Y77")
Can someone help me?
function createTriggers() {
ScriptApp.newTrigger("onEdit")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onEdit()
.create();
ScriptApp.newTrigger("onChange")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onChange()
.create();
}
function ContaCelleUnite(specifiText, inputRangeFormula) {
var sheet = SpreadsheetApp.getActiveSheet();
if (inputRangeFormula && inputRangeFormula.trim() !== "") {
var inputRange = sheet.getRange(inputRangeFormula).getA1Notation();
var numColonneTotale = 0;
var mergedRanges = sheet.getRange(inputRange).getMergedRanges();
for (var i = 0; i < mergedRanges.length; i++) {
var mergedRange = mergedRanges[i];
var mergedValues = mergedRange.getValues();
if (mergedValues[0][0].toString().includes(specifiText)) {
numColonneTotale += mergedRange.getNumColumns();
}
}
return numColonneTotale;
} else {
return "InputRangeFormula non valida";
}
}
function onEdit(e) {
if (e) {
var range = e.range;
var formula = range.getFormula();
if (formula.includes("ContaCelleUnite")) {
var formulaArgs = formula.match(/[(](.*?)[)]/)[1].split(",");
var specificText = formulaArgs[0].replace(/"/g, "").trim();
var inputRangeFormula = formulaArgs[1].trim();
var sheet = range.getSheet();
var inputRange = sheet.getRange(inputRangeFormula).getA1Notation();
var result = ContaCelleUnite(specificText, inputRange);
Logger.log("Risultato: " + result);
range.setValue(result);
}
}
}
function onChange(e) {
if (e && e.range) {
var range = e.range;
var cellValue = range.getValue();
if (cellValue.includes("ContaCelleUnite")) {
var formulaArgs = cellValue.match(/[(](.*?)[)]/)[1].split(",");
var specificText = formulaArgs[0].replace(/"/g, "").trim();
var inputRangeFormula = formulaArgs[1].trim();
var sheet = range.getSheet();
var inputRange = sheet.getRange(inputRangeFormula).getA1Notation();
var result = ContaCelleUnite(specificText, inputRange);
Logger.log("Risultato: " + result);
range.setValue(result);
}
}
}